debugjavascriptMajorpending
Debug: JavaScript memory leaks in SPAs
Viewed 0 times
memory leakspaevent listenerdetached domheap snapshotclosure
Error Messages
Problem
Single-page application's memory usage grows over time, eventually becoming slow or crashing.
Solution
Find and fix SPA memory leaks:
// 1. Use Chrome DevTools Memory tab
// Performance > Memory checkbox > Record
// Heap snapshot > Compare snapshots
// Allocation timeline > See what's growing
// 2. Common leak patterns and fixes:
// LEAK: Event listeners not cleaned up
function initFeature() {
window.addEventListener('resize', handleResize);
// Never removed! Accumulates on each route change
}
// FIX: Clean up in component unmount/destroy
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
// LEAK: setInterval not cleared
function startPolling() {
setInterval(() => fetchData(), 5000);
// Interval runs forever, even after navigating away
}
// FIX: Store and clear the interval
useEffect(() => {
const id = setInterval(() => fetchData(), 5000);
return () => clearInterval(id);
}, []);
// LEAK: Closures holding references
function createHandler(element) {
const data = fetchLargeDataset(); // 10MB
element.onclick = () => {
console.log(data.length); // Closure keeps data alive
};
}
// FIX: Only capture what you need
function createHandler(element) {
const count = fetchLargeDataset().length;
element.onclick = () => console.log(count);
}
// LEAK: Detached DOM nodes
// Elements removed from DOM but still referenced in JS
// LEAK: Observables/subscriptions not unsubscribed
// RxJS, MobX, custom event emitters- Three-snapshot technique: Take heap snapshot, perform action, take snapshot, undo action, take snapshot. Compare 1 and 3 - growth = leak.
Why
SPAs don't get natural cleanup from page navigation. Every navigation within the SPA accumulates listeners, timers, and closures unless explicitly cleaned up.
Context
Single-page applications with growing memory usage
Revisions (0)
No revisions yet.