A React component keeps listeners or fetches alive after it leaves
Handlers keep firing after the component is goneShort 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.
Fix it fast
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=*.tsx2Match what you see, then jump to its fix
- 1
A 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
Switching quickly between items shows the previous item's dataA fetch finishes after the data it was for is outdatedFix - 3
The Effect logs twice on mount, only in developmentStrict Mode runs the Effect twice in developmentFix
- 1
What does the error look like?
Handlers keep firing after the component is goneA slow response from an old request overwrites newer dataEffect 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(" src2Fix
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 pageConfirmed by react.dev
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=*.tsx2Fix
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 itemsConfirmed by react.dev
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" src2Fix
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 orderConfirmed by react.dev
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Axios get works with a URL string but ignores the object passed as the second argument
The server log shows a GET with no query string
axios.get takes a URL and an optional config object.
3 causes, each with a fixWeb apps
Can't resolve '../axios' in a React project
Module not found: Error: Can't resolve '../axios'
A path that starts with ./ or ../ is a file path, not the axios package.
3 causes, each with a fixWeb apps
Axios returns 401 from a React app but the login works elsewhere
Error: Request failed with status code 401
A 401 means the server received the request without valid credentials.
3 causes, each with a fixWeb apps
An axios call never finishes when the API server stops answering
code: 'ECONNABORTED'
Axios has no timeout unless you give it one: the default is 0, which means wait forever.
3 causes, each with a fix