JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext
performance
senior
memory

How do you identify and fix memory leaks in JavaScript applications?

memory-leaks
garbage-collection
profiling
weakmap
Quick Answer

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.

Detailed Explanation

Detection Tools:

  • Memory tab in DevTools
  • Heap snapshots comparison
  • Allocation timeline
  • Performance monitor

Common Memory Leaks:

  1. Event listeners not removed
  2. Timers/intervals not cleared
  3. Detached DOM with JS references
  4. Closures capturing large scopes
  5. Global variables accumulating
  6. Cache without bounds

Prevention:

  • Clean up in useEffect return
  • Use WeakMap for metadata
  • Implement cache eviction
  • Remove listeners on unmount
  • Clear timers/intervals

Code Examples

Common leak patterns and fixes
// 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);
    };
  }, []);
}

Resources

Chrome DevTools - Memory Problems

docs

Web.dev - Memory Leaks

article

Related Questions

How do you identify and fix JavaScript runtime performance issues?

senior
runtime
Previous
How do you identify and fix JavaScript runtime performance issues?
Next
How do service workers improve performance and what caching strategies exist?