Cleanup and race conditions in effects
Cleanup functions, AbortController, avoiding setState after unmount, and fixing the classic stale-request race condition with a worked example.
Data fetching in effectsuseEffect and synchronizing with external systems
Cleanup and race conditions in effects
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A cleanup function is whatever your effect's setup function returns, and React calls it before the effect re-runs and again when the component unmounts for good.
- Cleanup exists to undo exactly what the setup function did: cancel a request, clear a timer, unsubscribe, remove an event listener — leaving anything behind leaks memory or triggers updates no one expects.
- Calling setState from a fetch callback after the component has unmounted doesn't crash modern React, but it is wasted work and a sign the effect isn't cleaning up after itself.
- The classic stale-request race happens when an earlier request resolves after a later one, and its callback overwrites state with outdated data because nothing told it the world had moved on.
- AbortController lets you cancel an in-flight fetch outright, which both frees the network resource and gives you a clean signal to ignore its result if it does resolve.
- A simpler cleanup-flag pattern — a local 'is this effect still current' boolean — fixes the same race without needing an AbortController, at the cost of still letting the request finish in the background.
Cleanup undoes setup
Every effect can optionally return a function, and that function’s whole job is to undo whatever the effect’s setup did:
useEffect(() => {
const id = setInterval(() => setTick((t) => t + 1), 1000);
return () => clearInterval(id); // undoes setInterval
}, []);
React calls that returned function in two situations: right before it runs the effect’s setup again (because a dependency changed), and once more when the component unmounts and the effect will never run again. If the setup subscribes, the cleanup unsubscribes. If the setup adds an event listener, the cleanup removes it. If the setup starts a fetch, the cleanup should cancel it. Skipping cleanup doesn’t usually crash anything immediately — it just leaks: extra timers ticking in the background, duplicate listeners piling up, or state updates arriving for a component that’s no longer on screen.
The bug: a fetch that outlives its component
Here’s a search box that fetches results as the user types, with no cleanup at all:
// Before: no cleanup, no cancellation
function Search({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
fetch(`/api/search?q=${query}`)
.then((res) => res.json())
.then((data) => setResults(data)); // can fire after unmount, or out of order
}, [query]);
return <ResultsList items={results} />;
}
Two different things can go wrong here, and they’re related:
- Unmount: if the user navigates away while the request is still in flight, the
.thencallback fires later and callssetResultson a component that no longer exists. - The race: if the user types
"re"and then quickly"react", two requests go out. The"re"request happens to be slower — maybe the server has to scan more rows — and its response lands after the"react"response. The lastsetResultscall wins, so the screen ends up showing results for"re"even though the user’s last keystroke was"react".
The race condition is the subtler bug: both requests fired correctly, both resolved correctly, and the bug is purely about order. Nothing here is actually broken except the assumption that responses arrive in the order requests were sent.
The fix: AbortController
// After: cancel the previous request before starting a new one
function Search({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
if (!query) {
setResults([]);
return;
}
const controller = new AbortController();
fetch(`/api/search?q=${query}`, { signal: controller.signal })
.then((res) => res.json())
.then((data) => setResults(data))
.catch((err) => {
if (err.name !== "AbortError") throw err; // ignore cancellations
});
return () => controller.abort(); // cancel this request on cleanup
}, [query]);
return <ResultsList items={results} />;
}
Now, every time query changes, React runs the previous effect’s cleanup first — which calls controller.abort() on the previous request — before starting the new one. The previous request’s fetch promise rejects with an AbortError, which the .catch recognizes and ignores instead of calling setResults with stale data. The same cleanup fires on unmount too, so a request from a component that’s no longer mounted gets cancelled rather than resolving into a setState call on a dead component.
The simpler alternative: a cleanup flag
Not every request can be cancelled — some libraries don’t support AbortController, or you’re wrapping an API that doesn’t take a signal. A plain boolean flag fixes the same race without cancellation:
useEffect(() => {
let isCurrent = true;
fetch(`/api/search?q=${query}`)
.then((res) => res.json())
.then((data) => {
if (isCurrent) setResults(data); // ignore if a newer effect has started
});
return () => {
isCurrent = false;
};
}, [query]);
The request still runs to completion in the background — this doesn’t save the network round trip the way AbortController does — but the stale result is simply discarded once a newer effect has superseded it. This is the right fallback when cancellation isn’t available, and it’s also simpler to reach for when the performance cost of letting a request finish doesn’t matter.
What the video covers
Theo’s video makes a broader case for AbortController as an underused browser API, with the useEffect cleanup wiring as one concrete application of it rather than the sole focus — he covers cancelling fetches generally, of which the stale-request race above is a specific, important case. Watch it for the wider argument for AbortController; this lesson isolates the cleanup-function mechanics and the race condition it solves, which the video treats as one example among several.
Where this fits
Cleanup functions solve problems with effects that reach outside the component. The next lesson turns to a different kind of persistent value — one that lives inside the component across renders without triggering a re-render when it changes: useRef and mutable values.
Check yourself
When does React call the function an effect returns?
Right before running the effect's setup function again on a later render where a dependency changed, and once more when the component unmounts for the last time — in both cases, it tears down what the previous setup function created.
What is the classic stale-request race condition?
It happens when a component fires a new request before an earlier one has resolved, and the earlier (slower) request's response arrives after the later (faster) one's — if nothing guards against it, the earlier request's callback runs last and overwrites the UI with outdated data.
What does AbortController actually do when used inside an effect's cleanup function?
It signals the in-flight fetch to cancel, which both stops the browser from continuing to download a response nobody needs and, when the fetch does reject because it was aborted, gives the code a clear signal to skip updating state with that cancelled request's result.
Besides AbortController, what is the other common fix for the stale-request race?
A local boolean flag set to true when the effect runs and flipped to false by its cleanup function; the fetch callback checks that flag before calling setState, so a response from a cancelled effect is simply ignored instead of overwriting newer state.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.