Interview questions
Why does useEffect need cleanup?
Leaks, stale closures, and Strict Mode double-invocation.
What is tested: understanding that cleanup prevents leaks and stale work. Any effect that subscribes, opens a timer, or starts a request must undo it when deps change or the component unmounts; React runs cleanup before the next effect and on unmount.
Cleanup is turning off the tap you opened; skip it and the sink — listeners, timers, memory — overflows, especially when React opens the tap twice to test you.
Key concepts
1
Cleanup also fixes race conditions: cancelling an in-flight fetch means an old response cannot overwrite newer state.
race conditions
2
In Strict Mode (dev), React intentionally mounts, unmounts, and remounts once to surface missing cleanup — effects that are not idempotent (double subscriptions, duplicate intervals) reveal the bug immediately.
Strict Mode
3
Follow-up: "why does my interval double in dev?" — Strict Mode double-invokes; the returned clearInterval cleanup makes it correct. Common wrong answer: disabling Strict Mode instead of adding cleanup.
Follow-up:Common wrong answer:clearInterval
jsx
useEffect(() => {
const socket = connect(roomId);
socket.on('msg', onMsg);
return () => socket.close(); // prevents duplicate/leaked connections
}, [roomId]);