Performance & Security

Memory Leaks

Memory leaks silently grow your app's memory usage until it crashes or slows to a crawl. Learn the six classic leak patterns, how to detect them with DevTools heap snapshots, and the fixes that prevent them for good.

What causes memory leaks in JavaScript?

A memory leak happens when your code keeps references to data it no longer needs, so the garbage collector can't free it. Common causes are event listeners and intervals that are never removed, growing caches or arrays, references to removed DOM elements, and closures holding large objects. Find them with the DevTools Memory panel by comparing heap snapshots.

const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
const id = setInterval(poll, 5000);

// cleanup (e.g. when a component unmounts)
controller.abort();
clearInterval(id);

The 6 Classic Leak Patterns

#1

Accidental globals

Assigning to undeclared variable creates window property that never dies

Fix: Use 'use strict' and always declare with let/const/var

#2

Forgotten event listeners

Listener closure holds reference to element/data after removal

Fix: Always removeEventListener on cleanup (or use AbortSignal)

#3

Detached DOM nodes

Element removed from DOM but still referenced in JS array/map

Fix: Remove JS references when removing DOM nodes, or use WeakRef

#4

Closure over large data

Inner function captures big object in its scope

Fix: Extract only the values you need before creating the closure

#5

Uncleaned timers

setInterval keeps firing, holding references to component/data

Fix: clearInterval/clearTimeout in cleanup functions

#6

Unbounded caches

Map/array grows indefinitely caching items that should expire

Fix: Use WeakMap for object-keyed caches, or LRU cache with max size

Weak References — The GC-friendly Collections

WeakMap

Keys/Ref: Objects only
Values: Any
GC behavior: Entry removed when key object is GC'd
Use for: Private data per object, DOM node metadata

WeakSet

Keys/Ref: Objects only (no values)
GC behavior: Entry removed when object is GC'd
Use for: Tracking visited nodes, preventing double-processing

WeakRef

Keys/Ref: Single object reference
GC behavior: deref() returns undefined when object is GC'd
Use for: Optional caches, observer patterns

Common Pitfalls

Assuming that removing a DOM node frees all associated memory automatically
If any JS array, map, or closure still holds a reference to the node, it won't be GC'd.
Using Map/Object for caching without any eviction policy — memory grows until tab crash
Use WeakMap for object-keyed data, or implement an LRU cache with a max-size limit.
Not returning cleanup functions from React useEffect — timers, listeners, subscriptions leak
Every useEffect that sets up something external MUST return a cleanup function that tears it down.
Calling setState on an unmounted React component — causes memory leak + React warning
Use AbortController to cancel fetch, or check a mounted ref: if (mountedRef.current) setState(...).

Interactive Demo

Code Editor

<button id="start">Start widget</button>
<button id="stop">Stop widget (cleanup)</button>
<p id="out">Ticks: 0</p>

Preview

Memory Leaks — step by step

1 / 4
1

Forgotten Event Listeners

Adding event listeners without removing them when a component or element is destroyed is a classic leak. The listener holds a reference to its callback, preventing garbage collection of the associated scope.

1 of 4
⚠️Profile with DevTools Memory Panel
Open Chrome DevTools, go to the Memory tab, and take heap snapshots before and after a suspected leak. The Allocation instrumentation on timeline view helps pinpoint exactly which call site allocates objects that never get freed.

🎯 Quick Check

Which pattern most commonly causes a memory leak in event-driven UI code?

JavaScript Memory Leaks: summary

Key points

  • Remove listeners and clear timers in cleanup functions (React useEffect return, component destroy).
  • Use WeakMap or WeakRef for caches keyed by objects that may go away.
  • Detached DOM nodes still referenced from JavaScript stay in memory.

Frequently asked questions

›How do I find a memory leak in Chrome?

Open DevTools → Memory, take a heap snapshot, repeat the suspicious action several times, take another snapshot, and compare them to see which objects keep growing.