Memory Profiling and Heap Snapshots in Production
Memory Profiling and Heap Snapshots in Production
Frontend memory leaks quietly degrade web application performance over prolonged sessions. In single-page applications (SPAs) where users keep tabs open for days (e.g. enterprise CRM, Slack, Trading desks), memory leaks cause tabs to consume gigabytes of RAM, resulting in sluggish scrolling, browser stutter, and eventually Out of Memory (OOM) tab crashes.
1. Common Culprits of Memory Leaks in React
- 1Forgotten Event Listeners: Attaching
window.addEventListenerwithout cleaning up inuseEffect. - 2Uncleared Timers:
setIntervalorsetTimeoutreferences holding closures of component scopes. - 3Detached DOM Nodes: JavaScript objects (caches, arrays, maps) holding references to DOM elements that have been removed from the visible document.
- 4Uncleared Observables / WebSockets: Unclosed RxJS subscriptions or WebSocket listener callbacks.
- 5Global Event Emitters: Registering handlers on singleton event buses without unregistering on unmount.
2. Taking Heap Snapshots in Chrome DevTools
To track memory leaks systematically:
- 1Open Chrome DevTools > Memory tab.
- 2Select Heap snapshot > click Take snapshot (Snapshot 1: Baseline).
- 3Perform the suspected action repeatedly (e.g., open and close an Analytics Modal 10 times).
- 4Click the trash can icon in the top left to force Garbage Collection (GC).
- 5Take Snapshot 2.
- 6Switch dropdown view from Summary to Comparison against Snapshot 1.
- 7Sort by Size Delta or filter by constructor:
- Search
Detachedto see Detached HTMLDivElement or unmounted components.
3. Code Example: Fixing a Detached DOM & Closure Leak
Leaky Implementation
Clean Enterprise Implementation
4. Retainer Trees in DevTools
When inspecting detached nodes in a heap snapshot, DevTools displays the Retainer Tree at the bottom:
Follow the retainer chain from top to bottom to locate the exact variable, closure, or event handler preventing the garbage collector from reclaiming the memory.
Practice Quiz
Typing Functional Components and Props in TypeScript
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.