CodePark/ questions / Effects
START PRACTICINGPRACTICE
Frontend question · React › Effects

What is an effect cleanup function, and when does React call it?

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);

The cleanup is the function you return from an effect. It should undo whatever the setup did. For example:

  • disconnect a socket
  • clear an interval
  • remove an event listener
  • abort a request

React calls the cleanup in two situations:

  • Before re-running the effect, because a dependency changed. React runs the previous cleanup with the previous values. Then it runs the new setup with the new values.
  • When the component unmounts. React runs the last cleanup.

In development under StrictMode, React also runs one extra setup and cleanup cycle right after mount. If your component breaks because of that, the cleanup is missing or incomplete.

The goal: setup followed by cleanup should leave no trace. The user should not be able to tell whether setup ran once or twice. Think of a light switch: turning it on and then off again leaves the room as it was.

  • The cleanup is the function returned from the effect, and it undoes the setup.
  • It runs before the next run of the effect, with the old values.
  • It runs when the component unmounts.
  • StrictMode adds a setup, cleanup, setup cycle, in development only.
  • Common uses are listeners, timers, subscriptions and aborting fetches.