Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

A React component keeps listeners or fetches alive after it leaves

ErrorHandlers keep firing after the component is gone

Short answer

An Effect leaks when it starts something and never stops it. Return a cleanup function from useEffect that removes listeners, closes connections and ignores or aborts a fetch that no longer matters. In development, Strict Mode runs the Effect twice on purpose; that is a check, not a leak.

  • Applies to React 19, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    List every Effect in the component and note what each one starts: a listener, a connection, or a request. Each of those needs something in its cleanup.

    grep -rn "useEffect" src --include=*.jsx --include=*.tsx
  2. 2Match what you see, then jump to its fix

    1. 1A handler still runs after you navigate away, or the number of handlers grows each time you returnAn event listener or subscription is never removedFix
    2. 2Switching quickly between items shows the previous item's dataA fetch finishes after the data it was for is outdatedFix
    3. 3The Effect logs twice on mount, only in developmentStrict Mode runs the Effect twice in developmentFix

What does the error look like?

  • Handlers keep firing after the component is gone
  • A slow response from an old request overwrites newer data
  • Effect logs twice on mount in development

Cause 1 of 3

An event listener or subscription is never removed

1Check

Look for addEventListener, connection.connect() or a subscribe call inside the Effect without a matching removal in a returned function.

grep -rn "addEventListener\|subscribe(\|connect(" src

2Fix

Return a cleanup function that undoes what the Effect did. React calls it before the Effect runs again and once when the component unmounts.

useEffect(() => {
  function handleScroll() {
    console.log(window.scrollX, window.scrollY);
  }
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, []);

3Verify

Mount and unmount the component several times; the handler should run once per scroll, not once per mount.

# add a console.log in handleScroll and scroll after leaving the page

Confirmed by react.dev

Did this fix it?

Cause 2 of 3

A fetch finishes after the data it was for is outdated

1Check

If the Effect depends on an id and awaits a request, an older response can arrive after a newer one. This is a race condition.

grep -rn "await\|fetch(" src --include=*.jsx --include=*.tsx

2Fix

Keep a local flag, set it in the cleanup, and skip the state update when it is set. You may also abort the request with AbortController, but the docs say that alone does not protect against races.

useEffect(() => {
  let ignore = false;
  async function startFetching() {
    const json = await fetchTodos(userId);
    if (!ignore) {
      setTodos(json);
    }
  }
  startFetching();
  return () => {
    ignore = true;
  };
}, [userId]);

3Verify

Switch between ids quickly; the screen must always end on the last one you chose.

# throttle the network in devtools and click between items

Confirmed by react.dev

Did this fix it?

Cause 3 of 3

Strict Mode runs the Effect twice in development

1Check

In development React mounts the component, runs the cleanup and mounts again to check your cleanup. In production the Effect runs once.

grep -rn "StrictMode" src

2Fix

Do not remove Strict Mode. Make the cleanup undo the setup, then the second run is harmless.

useEffect(() => {
  const connection = createConnection();
  connection.connect();
  return () => connection.disconnect();
}, []);

3Verify

Only one connection is active at a time in the dev tools or logs.

# log connect and disconnect and read the order

Confirmed by react.dev

Did this fix it?

How do I stop it coming back?

  • Write the cleanup at the same moment you write the setup.
  • Pair every addEventListener with a removeEventListener using the same function.
  • Guard state updates after await with an ignore flag when the Effect depends on props.
  • Keep Strict Mode on in development so missing cleanups show up early.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.