Lingua-e
← Errors
JavaScript

Event Listener Memory Leak: What It Means and How to Fix It

Error reference

Event Listener Memory Leak

Language

JavaScript

Severity

Low

When it happens

Event listener memory leaks occur when listeners are added repeatedly without being removed, causing the count to grow indefinitely.

Potential fixes

Always store listener references and remove them when they are no longer needed. In React, return a cleanup function from useEffect. Use AbortController to remove multiple listeners at once. Use { once: true } for listeners that should fire only one time.

Deep dive

Event listener memory leaks occur when listeners are added repeatedly without being removed, causing the count to grow indefinitely. Each listener holds a reference to its closure, preventing garbage collection of the objects it captures. This leads to increased memory usage and potential CPU overhead.

Why it happens

  • Adding a listener inside a function that is called multiple times without removing the old one.
  • In React, adding a global listener in useEffect without returning a cleanup function.
  • Anonymous arrow functions used as listeners cannot be removed with removeEventListener.
  • Single-page applications that re-run setup code on every navigation without teardown.

Potential fixes

Always store listener references and remove them when they are no longer needed. In React, return a cleanup function from useEffect. Use AbortController to remove multiple listeners at once. Use { once: true } for listeners that should fire only one time.

Examples

JavaScript

Code that triggers the error

// Called on every route change
function setup() {
  window.addEventListener("resize", () => {
    console.log("resized");
  });
}

Error output

// No immediate error, but memory and CPU usage grow over time.
// Chrome DevTools > Memory > Heap snapshot shows growing listener count.

Fixed code

function handleResize() {
  console.log("resized");
}

function setup() {
  window.addEventListener("resize", handleResize);
}

function teardown() {
  window.removeEventListener("resize", handleResize);
}

Practice in English

How would you explain an Event Listener Memory Leak to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free