Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Concepts and Pitfalls

Race conditions in effects

Why slow responses can overwrite newer data when fetching in a React effect, and how an ignore flag or AbortController in the cleanup fixes the bug.

A race condition happens when the result depends on which of two asynchronous operations finishes first. In React it usually looks like this: a component fetches data for id = 1, the user switches to id = 2 a moment later, and the response for 1 arrives after the response for 2. If the effect saves every response it receives, the screen ends up showing user 1's data under user 2's title.

Networks do not guarantee order, so this bug appears intermittently, usually on slow connections and rarely on the developer's fast machine. The fix is to make the effect's cleanup mark the earlier request as obsolete, so a late answer is ignored.

JSX
useEffect(() => {
  let ignore = false;
  load(id).then((data) => {
    if (!ignore) setData(data);
  });
  return () => { ignore = true; };
}, [id]);

Try it

A fake API answers slowly for id 1 and quickly for id 2. Click "Load 1" and then "Load 2" immediately. In the buggy version, the slow answer for 1 overwrites the correct answer for 2.

The bug: last response wins

The fix has two flavors. The ignore flag throws away a late answer. AbortController also tells the browser to cancel the request, which frees bandwidth. A real fetch rejects with an AbortError when aborted, so that error is filtered out. This demo simulates it with a timer.

The fix: cleanup with a flag and an abort signal

Syntax

The pattern has three parts:

Part Purpose
A per-effect variable (let ignore = false) Remembers "this run is obsolete". Each effect run has its own copy, captured by the closure.
return () => { ignore = true; } The cleanup, which React calls before the next run and on unmount.
if (!ignore) setState(...) Applies the result only when this run is still the current one.
AbortController (optional) controller.abort() in cleanup cancels the actual request; pass controller.signal to fetch. Aborted fetch calls reject with an AbortError.
JSX
const controller = new AbortController();
fetch('/api/user/' + id, { signal: controller.signal });
return () => controller.abort();

Usage notes

  • Cleanup is the whole trick. Because each effect run has its own closure, the old run's flag is flipped by its own cleanup while the new run starts with a fresh false.
  • StrictMode helps find the bug. In development the effect runs, cleans up and runs again on mount; without the flag you would see two requests and two state updates.
  • Reset state at the start of the effect (setUser(null)) if you do not want to show the previous user's data while the new one loads.
  • Errors need the same guard. Check ignore before setting an error state, so an old failure does not replace new data.
  • Not just fetch: any async work started in an effect (promises, timers, WebSocket messages) can finish late.
  • Libraries do this for you. TanStack Query, SWR, React Router loaders and framework data APIs handle cancellation and caching; prefer them for non-trivial fetching.
  • Event handlers can race too. A search box that fires a request per keystroke needs the same protection, such as a request counter in a ref.
  • use with Suspense avoids hand-written effects for reading promises; see use.