Use Chrome DevTools Memory tab to take heap snapshots and compare them over time. Common leaks include detached DOM nodes, forgotten event listeners, closures holding references, and uncleared timers. Fix by proper cleanup in useEffect, removing listeners, and using WeakMap.
Detection Tools:
Common Memory Leaks:
Prevention:
// LEAK: Event listener not removed
class Component {
constructor() {
window.addEventListener('resize', this.handleResize);
}
// Missing cleanup - listener persists after component destroyed!
}
// FIX: Clean up listeners
class Component {
constructor() {
this.handleResize = this.handleResize.bind(this);
window.addEventListener('resize', this.handleResize);
}
destroy() {
window.removeEventListener('resize', this.handleResize);
}
}
// LEAK: React component without cleanup
function BadComponent() {
useEffect(() => {
const interval = setInterval(updateData, 1000);
window.addEventListener('scroll', handleScroll);
// No cleanup!
}, []);
}
// FIX: Proper useEffect cleanup
function GoodComponent() {
useEffect(() => {
const interval = setInterval(updateData, 1000);
window.addEventListener('scroll', handleScroll);
return () => {
clearInterval(interval);
window.removeEventListener('scroll', handleScroll);
};
}, []);
}