🚰 Memory Leaks
jsadvanced

🚰Memory Leaks

Memory leaks occur when unused objects remain referenced, preventing garbage collection. Common causes: event listeners, closures, timers, detached DOM nodes.

Log in to track your mastery & progress

1️⃣ What is a Memory Leak?

A memory leak occurs when memory that is no longer needed is not released, causing memory usage to grow over time.

JavaScript uses garbage collection (mark-and-sweep), but GC can only free objects with zero reachable references.

Leak = Unintentional reference retention.

2️⃣ Common Causes

CauseExampleFix
Event listenersNever removing listenersUse removeEventListener or cleanup
TimerssetInterval not clearedclearInterval on unmount
ClosuresCapturing large objectsNarrow closure scope
Detached DOMRef to removed elementSet ref to null after removal
Global variablesAccidental globalsUse strict mode
React effectsMissing cleanupReturn cleanup from useEffect
js
// Leak: listener never removed button.addEventListener('click', heavyHandler); // Fix button.addEventListener('click', heavyHandler); // Later: button.removeEventListener('click', heavyHandler);

3️⃣ Detecting Memory Leaks

In Chrome DevTools:

  1. Memory tab → Take Heap Snapshot
  2. Perform action (navigate, click)
  3. Take another snapshot
  4. Compare: look for retained objects that shouldn't be there
  5. Look for Detached DOM nodes (elements removed from DOM but still referenced in JS)

In React:

  • Missing cleanup in useEffect → listeners, subscriptions accumulate
  • State updates on unmounted components (shows warning)

Was this helpful?

Test your Knowledge

2 questions to cement what you just learned.