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
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div></div>
<script type="text/babel">
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>);
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<App/>);
</script>
</body></html><!DOCTYPE html><html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div></div>
<script type="text/babel">
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>);
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Example/>);
setTimeout(()=>{ // simulating unmounting after 5 seconds
root.unmount();
},5000);
</script>
</body></html>