When does the cleanup function returned from useEffect run?
React runs it before the effect runs again and when the component unmounts. Use it to undo what the effect set up: clear timers, remove listeners, close connections or cancel requests.
Explain it simply
Think of switching on a geyser each morning. Before you switch it on again, you must switch off the previous run, or two geysers would be heating at once. The cleanup function is the switch-off.
It runs with the old values, right before the next effect with new values, and one last time when the component leaves the screen. So for an effect that depends on [roomId], moving from room 1 to room 2 first cleans up room 1 and only then sets up room 2.
Typical jobs for cleanup are clearing a setInterval, removing an event listener added to window, unsubscribing from a store, closing a WebSocket, and aborting a fetch that is no longer needed.
Example
function Clock() {
const [t, setT] = useState(0);
useEffect(() => {
const id = setInterval(() => setT(x => x + 1), 1000);
return () => clearInterval(id); // stops the old timer
}, []);
return <p>{t}s</p>;
}Without the cleanup, every mount adds a new interval that keeps running after the component is gone.
What to say in the interview
"The function returned from an effect is the cleanup. React calls it before re-running the effect and on unmount. I use it for timers, event listeners, subscriptions and aborting fetches. In Strict Mode development, React mounts, unmounts and remounts once, which exposes missing cleanups."
Common mistakes
- Forgetting to clear intervals or listeners, which leaks memory and duplicates work.