Skip to the page

Keeping it fast · mid

Memory leaks in long-lived pages

A leak is memory that stays reachable after you no longer need it, usually through forgotten listeners, timers, subscriptions, caches or detached DOM nodes, and you find it by repeating an action and comparing heap snapshots after forced garbage collection.

The notes

What you must know

  • Garbage collection frees only unreachable objects. A leak = something still holds a reference: a global, a closure in a listener, a timer, a Map cache, a detached DOM node.
  • Common SPA leaks: event listeners on window/document not removed on unmount, setInterval not cleared, subscriptions (WebSocket, store, observer) not closed, growing module-level caches, closures capturing large data.
  • In React, every effect that subscribes must return a cleanup function. Use AbortController to cancel fetches on unmount.
  • Detached DOM nodes: elements removed from the page but still referenced from JS; they keep their whole subtree alive.
  • Find it: DevTools Performance with the Memory checkbox (JS heap and node count should return to baseline after GC); Memory panel heap snapshots before and after repeating an action, filter 'Detached', read the retainers; allocation timeline.
  • WeakMap/WeakRef let a cache entry be collected when the key object is gone; bound caches (LRU) for everything else.

The red pen

Common traps: mistake → fix

  • Mistake: "JavaScript has GC, so leaks can't happen"

    Fix: GC only frees unreachable memory; references you forget keep it alive.

  • Mistake: "Memory going up and down is a leak"

    Fix: a sawtooth is normal GC; a leak is a baseline that keeps rising after forced GC.

  • Mistake: "Removing the element from the DOM frees it"

    Fix: it stays alive if any JS still references it.

Easy to hard

Questions interviewers ask, easy to hard

  1. How can a single-page app leak memory? Give three examples.
  2. How would you find a leak in a dashboard tab that stays open all day?
  3. What is a detached DOM node?
  4. How do WeakMap and WeakRef help, and when are they the wrong tool?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview