Skip to main content

React Memory Management

Memory leaks are invisible until they crash production. The app works in development. It dies at scale.

Every subscription, listener, and timer that outlives its component is a leak. React unmount is your last chance to clean up.

Leak Sources

SourceHow It LeaksFix
setInterval / setTimeoutRuns after unmountClear in useEffect cleanup
Event listenersaddEventListener without removalReturn cleanup from useEffect
WebSocket connectionsStay open after navigationClose on unmount
AbortController missingFetch completes after unmount, sets stateAbort in cleanup function
Closures over stale stateHold references to unmounted component treeUse refs or proper dependency arrays
Large object refsStored in state or context, never releasedNull out on unmount
Third-party librariesMap instances, chart objects, editorsCall .destroy() or .dispose() in cleanup

Detection Checklist

MethodWhat It ShowsWhen
Chrome DevTools Memory tabHeap snapshots, allocation timelineSuspected leak
React DevTools ProfilerUnnecessary re-renders holding refsPerformance degradation
why-did-you-renderIdentifies wasted rendersDevelopment
Node --inspect + heap dumpServer-side memory in API routesServer memory growth
Vercel/hosting metricsMemory usage over timeProduction monitoring

Prevention Pattern

useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal });

return () => controller.abort(); // Always clean up
}, [url]);

Every useEffect with a side effect needs a cleanup return. No exceptions.

Context

  • Performance — Memory and performance are the same problem
  • Anti-patterns — Memory leaks are the silent anti-pattern
  • Hooks — useEffect cleanup is the primary defense
  • State Management — Global state that never releases is a leak

Questions

How do you detect a memory leak before users report crashes?

  • What is the cost of a memory leak that only manifests after 30 minutes of use?
  • When does server-side memory management differ from client-side in Next.js?
  • How do third-party map and chart libraries change your cleanup obligations?