Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 06 / Topic 3 of 7

Cleanup functions: a live clock that doesn't leak

Some effects start something ongoing - a timer, a subscription, a listener - that has to be stopped, not just started. examples/02_live_clock_cleanup.jsx's LiveClock starts a setInterval and returns a function from its effect:

// examples/02_live_clock_cleanup.jsx
export function LiveClock() {
  const [secondsElapsed, setSecondsElapsed] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSecondsElapsed((current) => current + 1);
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);

  return <p>Live for {secondsElapsed}s</p>;
}

That returned function is the cleanup function. React calls it right before the effect runs again, and once more when the component unmounts - here, never (the dependency array is []), so the only cleanup call LiveClock ever gets is on unmount, which is exactly when the interval needs to stop. LiveClockLeaky, in the same file, is the same component with that return line deleted. Rendering LiveClock, unmounting it, and checking Vitest's own fake-timer queue really shows the interval is gone (examples/02_live_clock_cleanup.test.jsx, vi.getTimerCount() reads 0); doing the exact same thing to LiveClockLeaky really leaves it at 1 - a timer still running, against a component that no longer exists, for as long as the real page stays open. Every mount/unmount of a screen using LiveClockLeaky (navigating to it and away, repeatedly) adds one more orphaned interval.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide