cleanup in useEffect
What the cleanup function does in useEffect
The cleanup function is the function you return from useEffect.
React calls it when it needs to "clean up" the consequences of the previous effect:
unsubscribe, stop a timer, cancel a request, remove a handler, and so on.
Syntax
javascript
useEffect(() => {
// side effect
console.log("Effect started");
return () => {
// cleanup - the cleanup function
console.log("Effect cleaned up");
};
}, []);When cleanup is called
| Situation | When cleanup is called |
|---|---|
| The component unmounts | Before the component is removed from the screen |
| The effect re-runs (dependencies changed) | Before the new effect runs |
| The effect was never called | Cleanup is not called either |
In simpler terms:
React does this:
- Run the effect
- If the dependencies have changed:
- call the cleanup of the old effect,
- then call the new effect
Example 1 - subscribing to an event
javascript
useEffect(() => {
function handleResize() {
console.log(window.innerWidth);
}
window.addEventListener("resize", handleResize);
console.log("Subscription set up");
// Cleanup: unsubscribe when the component is removed
return () => {
window.removeEventListener("resize", handleResize);
console.log("Subscription removed");
};
}, []); // only on mountWhat happens:
- On mount: an event listener is added.
- On unmount: the listener is removed (cleanup).
Example 2 - an effect with a dependency
javascript
useEffect(() => {
const timer = setInterval(() => console.log("tick"), 1000);
return () => {
clearInterval(timer); // clean up the old interval
};
}, [count]);Here, every time count changes:
- React calls cleanup ->
clearInterval(timer) - Then it starts a new
setInterval
This prevents several timers from "piling up" at the same time.
Why cleanup is needed
Prevents memory leaks (for example, unclosed subscriptions, timers). Avoids duplicate effects when dependencies update. Ensures the correct "lifecycle" of the component (mount -> update -> unmount).
Summary
| Question | Answer |
|---|---|
| What cleanup does | Cleans up the effect's consequences (subscriptions, timers, requests, etc.) |
| When it is called | Before the effect runs again and when the component unmounts |
| Why it is needed | To avoid memory leaks and duplicate side effects |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.