Run a React hook when a component Unmounts

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

Run a React hook when a component Unmounts #

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.

App.js
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 function when 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;

run react hook on unmount

We used the useEffect hook to run some logic when a component unmounts.

App.js
useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); // 👇️ run function when 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 parameter we passed to useEffect is a dependencies array. The hook from the example does not depend on any external variables, so the dependencies array is empty.

The function we passed to 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 don't want to run any logic when the component mounts, you can directly return your cleanup function.

App.js
useEffect(() => { // 👇️ run function when component unmounts 👇️ return () => { console.log('Child unmounted'); }; }, []);
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.