JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext

Learn the concept

Memory Leaks & Management

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 fixesJavaScript
// 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);
    };
  }, []);
}

Real-World Applications

Use Cases

Investigating unexplained long-term memory growth in a single-page application (SPA)

Using Chrome DevTools' Memory tab to take heap snapshots at different points, comparing them to identify new objects being retained in memory without being garbage collected, indicating a potential leak.

Optimizing a frequently mounted/unmounted React component that causes memory build-up over time

Ensuring all event listeners, timers, subscriptions, and other external resources are properly cleaned up in the component's `useEffect` cleanup function or `componentWillUnmount` lifecycle method.

Preventing accidental retention of large objects within closures in a utility library

Carefully structuring functions and their scopes to avoid unintended capture of heavy data structures by inner functions that persist longer than expected, leading to memory bloat.

Mini Projects

Memory Leak Detection with DevTools

intermediate

Create a small web application that intentionally introduces common memory leaks (e.g., forgotten event listener, uncleaned timer) and then use Chrome DevTools to locate and diagnose them.

React Component with Cleanup

beginner

Develop a React component that subscribes to a global event or sets up an interval, and correctly implement cleanup logic using `useEffect` to prevent memory leaks when the component unmounts.

Industry Examples

Slack

As a long-running communication platform, Slack's desktop application (built with Electron, essentially a web app) meticulously monitors and optimizes memory usage to ensure a smooth, responsive experience for users who keep the app open for extended periods, actively hunting and fixing memory leaks.

VsCode

Microsoft's VS Code, another Electron-based application, employs advanced memory profiling techniques to maintain high performance and low resource consumption. Preventing memory leaks is crucial for an editor that users interact with for hours daily across various projects.

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?
PrevNext