What is Cleanup Function in useEffect in React
cleanup function inside useEffect runs before the component unmounts or before the effect runs again. It helps to clean up resources like timers, subscriptions, or event listeners to avoid memory leaks and unwanted behavior.How It Works
Think of the useEffect hook as a way to perform side tasks in your component, like setting up a timer or subscribing to data. The cleanup function is like tidying up your workspace before you leave or before starting a new task. It runs right before the component is removed from the screen or before the effect runs again due to changes.
This cleanup prevents problems like multiple timers running at once or leftover event listeners that slow down your app. It’s similar to turning off a faucet before leaving the house to avoid wasting water.
Example
This example shows a timer that counts seconds. The cleanup function clears the timer when the component unmounts or before the timer restarts, preventing multiple timers from running simultaneously.
import React, { useState, useEffect } from 'react'; function Timer() { const [count, setCount] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setCount(c => c + 1); }, 1000); // Cleanup function to clear the interval return () => { clearInterval(intervalId); console.log('Timer cleaned up'); }; }, []); // Empty dependency array means this runs once return <div>Seconds passed: {count}</div>; } export default Timer;
When to Use
Use the cleanup function whenever your effect creates something that needs to be stopped or removed later. Common cases include:
- Clearing timers or intervals
- Removing event listeners (like window resize or scroll)
- Canceling network requests or subscriptions
- Cleaning up third-party libraries or animations
This keeps your app fast and prevents bugs caused by leftover processes running after a component is gone.
Key Points
- The cleanup function runs before the component unmounts or before the effect runs again.
- It helps prevent memory leaks and unwanted side effects.
- Always return a cleanup function from
useEffectif your effect sets up subscriptions, timers, or listeners. - Without cleanup, your app can slow down or behave incorrectly over time.