Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 83

Memory Leaks: Common Causes & Solutions

This lesson is built with resources from youtube.com, trevorlasn.com and 1 more site.

Hello! Welcome back to our module on Memory Management and Performance Profiling.

In our previous lesson, you gained a crucial practical skill: using browser DevTools and heap snapshots to find detached DOM nodes. We learned how to identify that a leak is happening. Today, we'll shift our focus to the why. This lesson will help you identify common causes of memory leaks, such as dangling event listeners and closure retention.

Understanding these underlying code patterns is essential. While the DevTools can show you what is leaking, recognizing why it's leaking is the key to writing robust, performant, and memory-efficient applications. We'll connect these abstract patterns back to the concrete tools you learned last time.

The Core Principle: Unwanted References

A memory leak in a garbage-collected language like JavaScript almost always boils down to one simple problem: an object that is no longer needed is still being referenced from somewhere the garbage collector considers "reachable."

A helpful mental model for this comes from the "Understanding and Debugging Memory Leaks" talk. A leak often occurs when a short-lived object (like a temporary data structure or a DOM element for a specific view) is accidentally stored in a long-lived object (like a global cache, a persistent event listener, or an un-cleared timer). This long-lived reference keeps the short-lived object alive forever, consuming memory.

Today, we'll examine the two most common ways this happens.


1. Dangling Event Listeners

This is one of the most frequent sources of memory leaks, especially in single-page applications (SPAs). A "dangling" or "unremoved" event listener is one that was attached to an element (often a global one like window or document) but was never removed, even after the component or view that attached it was destroyed.

Why is this a leak? Because the event listener's handler is a function—often a closure. This function holds references to its entire creation scope. If that scope included large data structures or references to DOM elements, they will be kept in memory as long as the listener is active.

The following video provides a concise explanation of this mechanism.

JavaScript Memory Leaks // The Biggest Sources and Fixes

Let's start with a clear, concise explanation of how adding listeners without removing them can cause memory to accumulate over time.

Watch from 04:11 to 05:41. Pay attention to how each call to addEventListener adds a new function to an internal list. If these functions aren't explicitly removed, they (and the data they reference via closures) are never garbage collected.

To fix this, you must always pair an addEventListener with a corresponding removeEventListener.

Let's look at a concrete code example.

Why do closures sometimes cause memory leaks?

The video gave a great overview. Now, let's examine a typical memory leak caused by an event listener and the corresponding fix in code.

Read the section titled 'Scenario 1: Event listeners with closures'. Compare the 'leaky' code with the 'fixed' code. Note that the fix requires storing a reference to the named or anonymous handler function so it can be passed to removeEventListener later. You cannot remove a listener that was added as a fresh arrow function, e.g., () => {}.

This directly connects to our last lesson. When an event listener's closure holds a reference to a DOM node that is later removed from the page, that node becomes "detached." The dangling listener is the retaining path that prevents the garbage collector from cleaning it up.

Given your experience with React, let's see how this pattern manifests in a modern component-based framework.

Why do closures sometimes cause memory leaks?

The useEffect hook in React is a common place for this type of leak to occur if not handled correctly. This article shows the right way to manage side effects like event listeners.

Read the section 'Real-world example: React component memory leak'. The key takeaway is the cleanup function returned from useEffect. This is React's built-in mechanism for performing exactly the kind of cleanup we've been discussing, ensuring the listener is removed when the component unmounts or the effect re-runs.


2. Unintentional Closure Retention

As we've seen, event listeners are a specific case of a more general problem: unintentional memory retention by closures. You know from your previous studies that a closure is a function that "remembers" the environment in which it was created. This is an incredibly powerful feature, but it's also a primary source of memory leaks if not managed carefully.

The leak occurs when a closure that captures a large amount of data from its parent scope is kept alive for longer than necessary.

This video provides an excellent visual of this exact problem.

JavaScript Memory Leaks // The Biggest Sources and Fixes

Now let's generalize from event listeners to the broader topic of closure retention. This segment explains the fundamental reason closures can cause leaks: they implicitly hold strong references to variables in their outer scope.

Watch from 02:13 to 04:11. Notice how the returned function fn1 keeps the large value from its parent scope alive. The fix demonstrated is crucial: if you only need a piece of the data (like its length), extract it into a separate variable first. This way, the closure only captures the small primitive value, allowing the large object to be collected.

When you're hunting for leaks in DevTools, this is what it can look like.

Chrome DevTools Memory Tab: Heap Snapshot Analysis
In the DevTools Memory panel, when you inspect a leaked object, the 'Retainers' path might lead you through one or more `(closure)` contexts. This is your signal that a closure is responsible for keeping the object in memory.

Besides being returned from a function, closures are often kept alive by timers and asynchronous callbacks.

Why do closures sometimes cause memory leaks?

Let's explore other common scenarios where long-lived closures can cause leaks. Timers and asynchronous callbacks are frequent offenders because they create closures that persist until an event happens in the future.

Read 'Scenario 2: Timers with closures' and 'Scenario 3: Callbacks in async operations'. For timers, notice the critical importance of clearInterval. For async operations, the idea that a callback keeps data alive until the operation completes is a subtle but important concept to grasp.

Test your understanding!

Analyze the following Node.js code snippet. It's intended to process incoming requests, but it has a memory leak.

const EventEmitter = require('events');
const dataEmitter = new EventEmitter();

function createLargeObject() {
  // Simulates a large object, e.g., from a database query
  return new Array(1e6).fill('some-data');
}

function handleRequest(req, res) {
  const largeData = createLargeObject();

  // A one-time event for this specific request
  dataEmitter.on('process-data', () => {
    console.log(`Processing data of size: ${largeData.length}`);
    // This event might be emitted much later by another part of the system
  });

  res.send('Request handled, processing will occur later.');
}

// Assume `handleRequest` is called for every incoming HTTP request.
  1. What is the primary cause of the memory leak?
  2. How does this relate to the concepts of closures and dangling listeners?
  3. What is a simple way to fix this leak?
Show answer
  1. Cause: The memory leak is caused by adding a new event listener to the global dataEmitter for every single request, but never removing it.

  2. Relation to Concepts:

    • Closures: The arrow function passed to dataEmitter.on() is a closure. It captures the largeData variable from the handleRequest scope.
    • Dangling Listeners: Each time handleRequest runs, a new listener is added to dataEmitter's list of listeners. Since dataEmitter is a long-lived, module-global object, and the listeners are never removed, they "dangle" forever. Each dangling listener holds onto its own largeData object, preventing it from being garbage collected even after the HTTP response has been sent.
  3. Fix: The listener should be removed after it has served its purpose. Since this is a one-time event, the once() method is the perfect solution. It automatically removes the listener after it has been invoked once.

    // Corrected code
    dataEmitter.once('process-data', () => { // Use .once() instead of .on()
      console.log(`Processing data of size: ${largeData.length}`);
    });
    

    Alternatively, if once() wasn't available, you would have to store the handler in a variable and manually call dataEmitter.removeListener() at the appropriate time.


Other Common Causes

While dangling listeners and closure retention are the most common culprits, it's worth being aware of a few others that follow the same underlying principle.

  • Accidental Global Variables: If you forget to declare a variable with let, const, or var in non-strict mode, it can be accidentally assigned to the global object (window in browsers). Global variables are roots for the garbage collector and never get collected unless manually nulled.
  • Caches: Storing objects in a global or long-lived Map or Array to act as a cache is a common pattern. If there is no mechanism to remove entries from the cache when they are no longer needed (a process called eviction), the cache will grow indefinitely, causing a leak.
  • Circular References: This occurs when object A holds a reference to object B, and object B holds a reference back to object A. Modern garbage collectors can usually handle simple cycles like this. However, when closures are involved in the cycle, it can become more difficult for the GC to determine if the objects are truly unreachable, and they may be leaked. We'll look at a solution to this in the next lesson.

Conclusion

You now have a solid mental framework for identifying the root causes of memory leaks in JavaScript. By combining the practical skills from the last lesson with the conceptual knowledge from this one, you are well-equipped to diagnose and fix these performance-degrading issues.

Key Takeaways:

  • Memory leaks in JavaScript are caused by unwanted references that keep objects "reachable" to the garbage collector.
  • Dangling event listeners are a primary cause. Always ensure you have a strategy for removing listeners when they are no longer needed, typically by using removeEventListener in a cleanup phase.
  • Closures can unintentionally keep large objects or entire scopes alive. Be mindful of what is being captured by long-lived closures (like timers or permanent callbacks) and try to limit the captured scope.
  • Global caches, accidental globals, and circular references are other patterns that follow the same principle of a long-lived object holding a reference to a short-lived one.

In our next lesson, we'll address a solution to some of these problems. We will explore how to use WeakMap and WeakSet to store object metadata without preventing garbage collection, which is the perfect tool for building caches that don't cause memory leaks.