Interview Q&A / React

BeginnerQuick answer1 min readUpdated 3 Oct 2026

When does the cleanup function returned from useEffect run?

SHORT ANSWER

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

jsx
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.

#useeffect#cleanup

Related questions

Practise more React questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open React quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.