How to Run Code on Unmount in React Components
In React, you run code on component unmount by returning a cleanup function inside the
useEffect hook. This cleanup function runs automatically when the component is removed from the UI.Syntax
Use the useEffect hook with a function that returns another function. The returned function is the cleanup code that runs on unmount.
useEffect(() => { ...; return () => { cleanup code }; }, []);- The empty dependency array
[]means the effect runs once on mount and cleanup runs on unmount.
javascript
import { useEffect } from 'react'; useEffect(() => { // code to run on mount return () => { // code to run on unmount (cleanup) }; }, []);
Example
This example shows a component that logs messages when it mounts and unmounts. The cleanup function inside useEffect runs on unmount.
javascript
import React, { useEffect, useState } from 'react'; function Timer() { useEffect(() => { console.log('Timer mounted'); return () => { console.log('Timer unmounted'); }; }, []); return <div>Timer is running...</div>; } export default function App() { const [showTimer, setShowTimer] = useState(true); return ( <> <button onClick={() => setShowTimer(!showTimer)}> {showTimer ? 'Hide' : 'Show'} Timer </button> {showTimer && <Timer />} </> ); }
Output
When Timer mounts: console logs 'Timer mounted'.
When Timer unmounts (button toggled): console logs 'Timer unmounted'.
Common Pitfalls
- Not returning a cleanup function inside
useEffectmeans no code runs on unmount. - Forgetting the empty dependency array
[]causes the effect and cleanup to run on every render, not just mount/unmount. - Using class components? The equivalent is
componentWillUnmount, but hooks are preferred now.
javascript
/* Wrong: cleanup function missing */ useEffect(() => { console.log('Mounted'); // no return => no cleanup on unmount }, []); /* Right: cleanup function returned */ useEffect(() => { console.log('Mounted'); return () => { console.log('Unmounted'); }; }, []);
Quick Reference
| Concept | Description | Example |
|---|---|---|
| useEffect Hook | Runs code on mount and cleanup on unmount | useEffect(() => { return () => { /* cleanup */ }; }, []); |
| Cleanup Function | Function returned from useEffect to run on unmount | return () => { console.log('Cleanup'); }; |
| Dependency Array | Empty array means effect runs once on mount and cleanup on unmount | useEffect(() => { ... }, []); |
Key Takeaways
Use the useEffect hook with a cleanup function to run code on unmount.
Return a function inside useEffect; this function runs when the component unmounts.
Include an empty dependency array [] to ensure cleanup runs only on unmount.
Avoid missing the cleanup function or omitting the dependency array to prevent unexpected behavior.
Hooks are the modern way; avoid class lifecycle methods for new React code.