download

Why does React StrictMode run useEffect twice, and what breaks?

Frontend~8 minReviewed 3 Dec 2026Free · No sign-in

Question

In development with <StrictMode>, mounting RoomMonitor for room-1 triggers two pings every 5000 ms and two pings on every window focus. Switching roomId to room-2 raises it to three pings (2 stale room-1 pings plus 1 for room-2), and pings keep firing after unmount.

"TSX"
function RoomMonitor({ roomId, onPing }: Props) {
  useEffect(() => {
    const id = setInterval(() => onPing(roomId), 5000);
    window.addEventListener("focus", () => onPing(roomId));
  }, [roomId, onPing]);

  return <div>Watching {roomId}</div>;
}
  1. Why does React 19 <StrictMode> run this effect twice on mount?
  2. Fix the timer and listener leaks cleanly.
  3. Why does guarding with useRef to skip the second run hide a real production bug?
Show hints (3)
  1. "STRICTMODE TESTS CLEANUP"

    In development, <StrictMode> runs setup -> cleanup -> setup on mount to expose effects that cannot stop and restart cleanly.

  2. "KEEP SAME HANDLER"

    Passing a new inline arrow function to removeEventListener removes nothing. Store const handleFocus = ... and pass the exact same function to add and remove.

  3. "PRODUCTION STILL RE-RUNS"

    Even without <StrictMode> in production, every roomId change runs cleanup before the next setup, and unmount runs cleanup once.

Show checked explanation

React <StrictMode> runs an extra setup -> cleanup -> setup cycle in development to check that your effect cleans up properly. Here the effect never returns a cleanup function, so timers and window listeners pile up on mount, every roomId change, and unmount. Return a cleanup that clears the interval and removes the exact same listener reference.

Buggy, anonymous-removeEventListener, useRef-guarded, and cleaned-up effect lifecycles (including StrictMode dev setup-cleanup-setup, prop updates, unmount, and AbortController cleanup) were simulated on Node.js v24.15.0 and asserted in Python 3.12.10 (no React DOM runtime installed); lifecycle rules checked against React 19 documentation. Checked by an editor other than the author.

Walkthrough

Think of every useEffect as a matched start and stop pair. React runs your cleanup function in two moments: right before re-running the effect with new dependencies, and when the component unmounts. In development, <StrictMode> adds one extra check on mount (setup -> cleanup -> setup) so missing cleanups show up right away instead of leaking quietly in production.

Lifecycle step (dev <StrictMode>)Buggy component (active timers / listeners)Fixed component (active timers / listeners)
Mount room-1 (setup -> cleanup -> setup)2 timers, 2 listeners (both room-1)1 timer, 1 listener (room-1)
Change prop room-1 -> room-23 timers, 3 listeners (2 stale)1 timer, 1 listener (room-2)
Unmount RoomMonitor3 leaked timers, 3 leaked listeners0 timers, 0 listeners

Store the handler reference and return cleanup:

"TSX"
function RoomMonitor({ roomId, onPing }: Props) {
  useEffect(() => {
    const handleFocus = () => onPing(roomId);
    const id = setInterval(handleFocus, 5000);
    window.addEventListener("focus", handleFocus);
    return () => {
      clearInterval(id);
      window.removeEventListener("focus", handleFocus);
    };
  }, [roomId, onPing]);

  return <div>Watching {roomId}</div>;
}

Notice handleFocus is defined once inside the effect. Calling window.removeEventListener("focus", () => onPing(roomId)) with a second inline function fails silently because JavaScript compares listener functions by reference.

Why a useRef "run once" hack backfires. Adding if (ranRef.current) return; ranRef.current = true; silences the double ping on mount in dev. In production, the user still switches from room-1 to room-2 (or navigates away and back), and now room-2 either never subscribes or leaks room-1's old timer and listener forever.

Common mistakes

  • Disabling <StrictMode> or adding a didRun ref guard to stop the second dev run. Both hide a missing cleanup that leaks in production on prop changes and unmount.
  • Passing a fresh arrow function to window.removeEventListener("focus", () => ...). Because it is a new function reference, the original listener stays attached.
  • Assuming cleanup runs only on unmount. React also runs the previous effect's cleanup before every dependency-driven re-run.
  • Forgetting AbortController or an ignore flag when fetching inside useEffect. A slow response from room-1 can overwrite room-2's state after roomId changes.

Follow-up questions

  • "How do you clean up an async fetch inside useEffect when roomId changes?" Create const controller = new AbortController() inside the effect, pass { signal: controller.signal } to fetch, and call controller.abort() in cleanup. Also track let ignore = false (set ignore = true in cleanup) so state updates are skipped even if a cached promise resolves late.
  • "What happens if the parent passes an inline onPing function on every render?" Because onPing changes reference on each render, the effect tears down and restarts the 5000 ms interval every render. Wrap onPing in useCallback in the parent, or read non-reactive callbacks through React's useEffectEvent so the timer stays steady.
  • "Does <StrictMode> double-invoke effects in production builds?" No. The extra setup -> cleanup -> setup probe runs only in development. Production still runs cleanup whenever dependencies change, when a component unmounts, or when React hides and restores offscreen state.

What a strong answer covers

Explains <StrictMode>'s dev setup -> cleanup -> setup probe, returns cleanup clearing both setInterval and the exact handleFocus reference, rejects useRef workarounds, and covers AbortController cleanup for async fetches.

Open in interactive practice deck →

Original OfferVibe question. Synchronizing with Effects (React) · useEffect reference (React) · StrictMode reference (React) · useEffectEvent reference (React) · AbortController (MDN).
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.