How do you fix race conditions in React useEffect data fetching?
IntermediateReact interview questionBy UIRound, updated 23 November 2026
Short answer
A useEffect race condition happens when an effect starts a request, its inputs change, and the older response arrives after the newer one and overwrites state. Fix it in the effect's cleanup: set an ignore flag so the stale result is dropped, or call abort() on an AbortController so the request is cancelled as well. Outside effects, a latest-request id does the same job, and data libraries handle it by caching per key.
The bug, step by step
A search box fetches results as the user types:
function Search() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
useEffect(() => {
if (!query) return;
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then(setResults); // whichever response lands last wins
}, [query]);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<ul>{results.map((r) => <li key={r.id}>{r.name}</li>)}</ul>
</>
);
}The user types "rea" and then "react" quickly. Two requests are in flight. The server answers "react" fast because it is cached, and "rea" slowly because it matches more rows. The timeline:
- Effect for "rea" starts request A.
- Effect for "react" starts request B.
- B resolves: the list shows results for "react".
- A resolves: the list now shows results for "rea", while the input still says "react".
Nothing in the code is wrong line by line. Each effect run closes over the same setResults, and setResults has no idea which run called it. Responses do not come back in the order requests were sent: server work, caches, retries and the network all vary per request. The rule is simple: a response from an effect run that React has already cleaned up must not touch state.
Basic fetching in effects is covered in how do you fetch data in React, and the dependency and cleanup rules in how useEffect works. This page is about the race itself and how the fixes differ.
Fix 1: an ignore flag in the cleanup
React runs the previous effect's cleanup before it runs the next effect. A local variable flipped in the cleanup marks that run as stale:
useEffect(() => {
if (!query) return;
let ignore = false;
searchApi(query).then((data) => {
if (!ignore) setResults(data);
});
return () => {
ignore = true;
};
}, [query]);Each run has its own ignore variable through its closure, so flipping it for run A does not affect run B. This works with any promise, including SDKs and libraries that do not accept a signal. The downside: request A still runs to completion. The browser downloads and parses a response nobody will see.
Fix 2: AbortController in the cleanup
Aborting is not just a smarter ignore flag. It tells the browser to cancel the request, which frees bandwidth and the connection, and on slow mobile networks that leaves room for the request that matters.
useEffect(() => {
if (!query) return;
const controller = new AbortController();
(async () => {
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (!controller.signal.aborted) setResults(data);
} catch (err) {
if (err.name !== "AbortError") setError(err);
}
})();
return () => controller.abort();
}, [query]);Details worth saying in an interview:
- Abort covers the body too. If the headers have arrived but the body is still streaming,
res.json()rejects with anAbortError. - Filter the
AbortError. A cancelled request is expected, not a failure, so do not show an error for it. - Still check
signal.abortedbefore setting state. If the chain awaits something the signal does not control, such as a second parsing step, the check catches it. It costs nothing. - The server may keep working. It sees the connection or stream closed, but whether it stops its own work depends on the server. Abort is safe for reads. For a mutation it does not undo anything that already reached the server.
Search-as-you-type with debounce and AbortController is the classic exercise for this exact bug.
Fix 3: a latest-request id in a ref
Effects have cleanups; event handlers do not. When a request starts from a click or a form submit, track which request is current:
const latestId = useRef(0);
const controllerRef = useRef(null);
async function runSearch(q) {
const id = ++latestId.current;
controllerRef.current?.abort(); // cancel the previous one as well
const controller = new AbortController();
controllerRef.current = controller;
try {
const data = await searchApi(q, { signal: controller.signal });
if (id === latestId.current) setResults(data); // only the newest request may write
} catch (err) {
if (err.name !== "AbortError" && id === latestId.current) setError(err);
}
}This is "latest wins" by construction. It also fits code outside React, such as a service or a store action. Abort the controller from an effect cleanup on unmount if the component can go away mid-request.
Comparing the fixes
| Ignore flag | AbortController |
Latest-request id | |
|---|---|---|---|
| Stops stale state updates | Yes | Yes | Yes |
| Cancels the network request | No | Yes | Only if combined with abort |
| Works with promises that take no signal | Yes | No | Yes |
| Works in event handlers | No cleanup to hook into | Needs a ref to the controller | Yes |
| Typical use | Third-party SDK calls | fetch in effects |
Submit, retry, store actions |
In practice you combine them: abort whatever can be aborted and guard the state update either way.
Why StrictMode makes the bug visible
In development, <StrictMode> mounts each component, runs the effect's cleanup and runs the effect again. A fetch effect therefore fires twice on mount. With a correct cleanup, the first request shows as cancelled in the network tab and only one result reaches state. Without a cleanup, both requests resolve and both call setResults. With identical inputs the screen often looks fine, but duplicate requests, double analytics events and doubled subscriptions are the same missing cleanup that causes the race when inputs change. The guide to why effects run twice and why Strict Mode renders twice explain what React is testing.
Debouncing does not fix it
Debouncing the query cuts the number of requests, which is good, but two requests can still overlap: a slow response for "rea" can land after the debounced request for "react" has started. Debounce for load, abort or ignore for correctness. You need both.
When to stop writing this by hand
Once several components fetch, or you need caching, retries and refetch on focus, move to a data library.
- TanStack Query stores each result under its
queryKey, so a late response for["search", "rea"]lands in that key's cache entry and never replaces what["search", "react"]shows. It passes asignalto yourqueryFn, and if you use it, queries that are no longer needed are cancelled.placeholderData: keepPreviousDatakeeps the old list visible while the new one loads. See what TanStack Query is and why to use it. - SWR is also keyed: the component reads the data for its current key, so a response for an older key does not replace it.
- React 19
usewith a cached promise. Store one promise per query in a cache and read it withuse(getSearch(query))inside<Suspense>. Render always reads the promise for the currentquery, so an old promise has nowhere to write. The cache is essential: a promise created during render is new every time and suspends forever, which a promise cache withreadandrefreshsolves. Pair it withuseDeferredValueso typing does not flash the fallback.
Framework loaders and Server Components avoid the client-side effect entirely for route data.
Follow-up questions interviewers ask
Does the cleanup run before the next effect or after?
Before. When query changes, React re-renders, commits, runs the previous run's cleanup with its old values, then runs the new effect. That ordering is what makes the ignore flag and abort reliable.
Is calling setState after unmount still a problem?
React 18 removed the "state update on an unmounted component" warning, because the update is simply ignored. The race is still a real bug while the component is mounted, and an unaborted request still wastes the network. A useIsMounted ref hides the warning but not the race, which replacing useIsMounted with an effect that aborts shows.
How do you avoid showing the previous query's results while the new one loads?
Store the query with the results, such as { query, items }, and derive loading as results.query !== query. Then the old list is never shown under the new input unless you decide to keep it as a placeholder.
Should you abort a POST when the component unmounts?
Usually not. The user asked for the change, and aborting the request does not guarantee the server did not apply it. Let mutations finish, ignore their result if the screen is gone, and make them idempotent if they can be retried.
What is the bug in an effect that lists an object as a dependency?
An object created during render is new every time, so the effect re-runs on every render, often in a loop with its own setState. Combined with no cleanup, you get both a request storm and stale responses, which is the scenario in debugging an infinite useEffect() loop.
Mistakes to avoid
Fixing the race with a debounce alone
Showing an error message for an
AbortErrorUsing one shared
ignorevariable outside the effect, so every run reads the same flagAssuming abort rolls back a mutation on the server
Passing a promise created during render to
use()
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Debug an infinite
useEffect()loop and prevent stale asynchronous responsesMedium35 min - Build search-as-you-type with debounce and
AbortControllerMedium35 minFree - Load a list, then the selected item's details, without races: abort, ignore stale responses and cache by idMedium40 min
- Build
useIsMounted, then replace it with an effect that aborts and ignores stale resultsMedium30 min - Check username availability in a signup form: debounce, ignore stale responses and re-check on submitMedium40 min
- Stop
use()from suspending forever: a promise cache withreadandrefreshHard45 min