Run a React hook when a component Unmounts

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# 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 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;

run react hook on unmount

The code for this article is available on GitHub

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 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.

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 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.

App.js
useEffect(() => { // ๐Ÿ‘‡๏ธ Run a function when the component unmounts ๐Ÿ‘‡๏ธ return () => { console.log('Child unmounted'); }; }, []);
The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev