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
AbortController: create one per effect run, passsignaltofetch, abort in the cleanup. The stale request rejects withAbortError, which you ignore. Also saves bandwidth.- Ignore flag:
let ignore = false;in the effect andignore = truein cleanup; only set state if!ignore. Works for any promise, including SDKs that do not support abort. - Request IDs: compare a counter stored in a ref with the ID of the response.
- 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 anAbortSignalto your query function. - Router loaders: React Router cancels in-flight loader requests when a newer navigation starts.
- 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";23type Profile = { id: string; name: string };45// Fix 1 + 2: abort the stale request AND ignore its result6export function ProfileCard({ userId }: { userId: string }) {7 const [profile, setProfile] = useState<Profile | null>(null);89 useEffect(() => {10 const controller = new AbortController();11 let ignore = false;12 setProfile(null);1314 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 dropped18 })19 .catch((e) => {20 if (e.name !== "AbortError") console.error(e);21 });2223 return () => {24 ignore = true;25 controller.abort();26 };27 }, [userId]);2829 return <p>{profile ? profile.name : "Loading…"}</p>;30}3132// Fix 3: request ids for promise-based SDKs without abort support33export 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-deps40 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.