MENU
Simulating componentWillUnmount()
In general, unless the effect does not reference any props nor state, we should move all functions needed by an effect inside the effect so that it is easy to see which props and states are needed by the effect and should be included in the dependencies list.
RESETRUNFULL
RESETRUNFULL
function Example({ someProp }) {
React.useEffect(() => {
function doSomething() { console.log(someProp); }
doSomething();
}, [someProp]);
return null;}function App() {
const [state, setState] = React.useState(1);
return (<div><Example someProp={state} />
<p>{state}</p>
<button onClick={() => setState(prev => prev + 1)}>+</button>
</div>);}ReactDOM.render(<App/>,document.querySelector("div"));
function Example() {
const [count, setCount] = React.useState(0);
React.useEffect(() => { // similar to componentDidMount() & componentDidUpdate()
document.title = `You clicked ${count} times`;
return ()=>{ // similar to componentWillUnmount() with []; optional
alert("Sorry to see you go!");
}
},[]); // prevents unintentional alert() call since no change in array;, optional
return (<div><p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
</div>);}ReactDOM.render(<Example/>,document.querySelector("div"));setTimeout(()=>{ // simulating unmounting after 5 seconds
ReactDOM.unmountComponentAtNode(document.querySelector('div'));},5000);