Lingua-e
JavaScript

What is a Event Listener Memory Leak?

← Errors

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.

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.

How to fix it

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.

Fixed code

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

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

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

Related errors

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