Last updated: Apr 7, 2024
Reading timeยท2 min
Use the useEffect
hook to run a react hook when a component unmounts. The
function we return from the useEffect
hook gets invoked when the component
unmounts and can be used for cleanup purposes.
import {useRef, useEffect, useState} from 'react'; function Child() { const ref = useRef(null); useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); // ๐๏ธ Run a function when the component unmounts ๐๏ธ return () => { console.log('Child unmounted'); element.removeEventListener('click', handleClick); }; }, []); return ( <div> <button ref={ref}>Click</button> </div> ); } const App = () => { const [isMounted, setIsMounted] = useState(true); return ( <div> <button onClick={() => setIsMounted(current => !current)}> Toggle child </button> <hr /> {isMounted && <Child />} </div> ); }; export default App;
We used the useEffect hook to run some logic when a component unmounts.
useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); // ๐๏ธ Run a function when the component unmounts ๐๏ธ return () => { console.log('Child unmounted'); element.removeEventListener('click', handleClick); }; }, []);
The function we return from useEffect
will get invoked when the component
unmounts.
The second argument we passed to useEffect
is a dependencies array.
The hook from the example doesn't depend on any external variables, so the dependencies array is empty.
useEffect
will get invoked when the component mounts and the function we returned will get invoked when the component unmounts.The cleanup function is often used to remove any previously added event listeners to avoid memory leaks.
If you get the error Can't perform a react state update on an unmounted component, click on the link and follow the instructions.
If you don't want to run any logic when the component mounts, you can directly return your cleanup function.
useEffect(() => { // ๐๏ธ Run a function when the component unmounts ๐๏ธ return () => { console.log('Child unmounted'); }; }, []);
You can learn more about the related topics by checking out the following tutorials: