FlashcardNot attempted
Memory leaks in SPAs
Recall it before you reveal
Name the four most common sources of memory leaks in a React/SPA app, and the fix for each.
useEffect(() => { const controller = new AbortController(); fetch('/api', { signal: controller.signal }) .then((r) => r.json()) .then(setData) .catch((e) => { if (e.name !== 'AbortError') throw e; }); window.addEventListener('resize', onResize); const id = setInterval(poll, 1000); return () => { controller.abort(); window.removeEventListener('resize', onResize); clearInterval(id); };}, []);Space to reveal
Show answer & explanation
Something long-lived keeps a reference, so the GC can't collect it:
- Event listeners on window/document →
removeEventListenerin the effect cleanup - Timers (
setInterval) →clearIntervalin cleanup - Pending async work that sets state after unmount →
AbortController, abort in cleanup - Subscriptions / global caches (stores, sockets, Maps keyed by DOM nodes) → unsubscribe; use
WeakMap
Find them with DevTools → Memory → heap snapshots (look for "Detached" DOM nodes).