Skip to main content

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

SituationWhen cleanup is called
The component unmountsBefore the component is removed from the screen
The effect re-runs (dependencies changed)Before the new effect runs
The effect was never calledCleanup is not called either

In simpler terms:

React does this:

  1. Run the effect
  2. 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 mount

What 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:

  1. React calls cleanup -> clearInterval(timer)
  2. 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

QuestionAnswer
What cleanup doesCleans up the effect's consequences (subscriptions, timers, requests, etc.)
When it is calledBefore the effect runs again and when the component unmounts
Why it is neededTo avoid memory leaks and duplicate side effects

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.