side effects react hook code example
Example 1: react useEffect
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
function LifecycleDemo() {
useEffect(() => {
console.log('render!');
return () => console.log('unmounting...');
}, [
return "I'm a lifecycle demo";
}
function App() {
const [random, setRandom] = useState(Math.random());
const [mounted, setMounted] = useState(true);
const reRender = () => setRandom(Math.random());
const toggle = () => setMounted(!mounted);
return (
<>
<button onClick={reRender}>Re-render</button>
<button onClick={toggle}>Show/Hide LifecycleDemo</button>
{mounted && <LifecycleDemo/>}
</>
);
}
ReactDOM.render(<App/>, document.querySelector('#root'));
Example 2: componentwillunmount hooks
useEffect(() => {
window.addEventListener('mousemove', () => {});
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
Example 3: React looping hooks to display in other hook
import React, { useState } from "react";
function App() {
const [list, setList] = useState(" ");
const [items, updateOnClick] = useState([ ]);
function updateList(event) {
const valueEntered = event.target.value;
setList(valueEntered);
}
function updateClick(){
updateOnClick(list);
}
return (
<input onChange={updateList} type="text" value={list} />
<button onClick={updateClick}>
<span>Add</span>
</button>
<div>
<ul>
{items.map(item => <li>{item}</li>) }
</ul>
</div>);}
export default App;