ReactMedium

Race conditions in fetching?

A fetching race condition happens when several requests are in flight and they resolve in a different order than they were sent, so an older response overwrites a newer one. In React this typically occurs when props or state that drive a fetch change quickly (search input, switching tabs or user IDs). Prevent it by cancelling or ignoring stale requests, or by using a data library that keys results by input.

Example

User types "rea" then "react". Requests go out in that order, but "rea" is slower and returns last, so the list shows results for "rea" while the input says "react".

Fixes

  1. AbortController: create one per effect run, pass signal to fetch, abort in the cleanup. The stale request rejects with AbortError, which you ignore. Also saves bandwidth.
  2. Ignore flag: let ignore = false; in the effect and ignore = true in cleanup; only set state if !ignore. Works for any promise, including SDKs that do not support abort.
  3. Request IDs: compare a counter stored in a ref with the ID of the response.
  4. Data libraries: TanStack Query and SWR store results per key (["search", query]), so a late response for an old key never replaces the current one; they also pass an AbortSignal to your query function.
  5. Router loaders: React Router cancels in-flight loader requests when a newer navigation starts.
  6. Transitions: React 19.3 renders transitions independently, but data correctness still depends on handling stale responses.

Related

  • Debouncing reduces the number of requests, but does not by itself prevent out-of-order responses.
  • Server-side: make mutations idempotent so retried or duplicated requests do not corrupt data.

Code example

tsx
1import { useEffect, useRef, useState } from "react";
2
3type Profile = { id: string; name: string };
4
5// Fix 1 + 2: abort the stale request AND ignore its result
6export function ProfileCard({ userId }: { userId: string }) {
7 const [profile, setProfile] = useState<Profile | null>(null);
8
9 useEffect(() => {
10 const controller = new AbortController();
11 let ignore = false;
12 setProfile(null);
13
14 fetch(`/api/users/${userId}`, { signal: controller.signal })
15 .then((r) => r.json())
16 .then((data: Profile) => {
17 if (!ignore) setProfile(data); // a response for an old userId is dropped
18 })
19 .catch((e) => {
20 if (e.name !== "AbortError") console.error(e);
21 });
22
23 return () => {
24 ignore = true;
25 controller.abort();
26 };
27 }, [userId]);
28
29 return <p>{profile ? profile.name : "Loading…"}</p>;
30}
31
32// Fix 3: request ids for promise-based SDKs without abort support
33export function useLatest<T>(load: () => Promise<T>, deps: unknown[]) {
34 const latest = useRef(0);
35 const [data, setData] = useState<T>();
36 useEffect(() => {
37 const id = ++latest.current;
38 load().then((d) => id === latest.current && setData(d));
39 }, deps); // eslint-disable-line react-hooks/exhaustive-deps
40 return data;
41}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app