Why does React StrictMode run useEffect twice, and what breaks?
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.
function RoomMonitor({ roomId, onPing }: Props) {
useEffect(() => {
const id = setInterval(() => onPing(roomId), 5000);
window.addEventListener("focus", () => onPing(roomId));
}, [roomId, onPing]);
return <div>Watching {roomId}</div>;
}- Why does React 19
<StrictMode>run this effect twice on mount? - Fix the timer and listener leaks cleanly.
- Why does guarding with
useRefto skip the second run hide a real production bug?
Show hints (3)
- "STRICTMODE TESTS CLEANUP"
In development,
<StrictMode>runssetup -> cleanup -> setupon mount to expose effects that cannot stop and restart cleanly. - "KEEP SAME HANDLER"
Passing a new inline arrow function to
removeEventListenerremoves nothing. Storeconst handleFocus = ...and pass the exact same function to add and remove. - "PRODUCTION STILL RE-RUNS"
Even without
<StrictMode>in production, everyroomIdchange 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-2 | 3 timers, 3 listeners (2 stale) | 1 timer, 1 listener (room-2) |
Unmount RoomMonitor | 3 leaked timers, 3 leaked listeners | 0 timers, 0 listeners |
Store the handler reference and return cleanup:
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 adidRunref 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
AbortControlleror anignoreflag when fetching insideuseEffect. A slow response fromroom-1can overwriteroom-2's state afterroomIdchanges.
Follow-up questions
- "How do you clean up an async
fetchinsideuseEffectwhenroomIdchanges?" Createconst controller = new AbortController()inside the effect, pass{ signal: controller.signal }tofetch, and callcontroller.abort()in cleanup. Also tracklet ignore = false(setignore = truein cleanup) so state updates are skipped even if a cached promise resolves late. - "What happens if the parent passes an inline
onPingfunction on every render?" BecauseonPingchanges reference on each render, the effect tears down and restarts the5000 msinterval every render. WraponPinginuseCallbackin the parent, or read non-reactive callbacks through React'suseEffectEventso the timer stays steady. - "Does
<StrictMode>double-invoke effects in production builds?" No. The extrasetup -> cleanup -> setupprobe 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 →