الانتقال إلى المحتوى
FrontendReact· 6 دقائق للقراءة

Fetching in useEffect Has a Race Condition You Haven't Noticed

Responses can arrive in any order. A cleanup that aborts or ignores the old request keeps the screen right.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

A support agent clicks through the ticket list quickly: ticket 1041, then 1042. The list highlights 1042, but the details panel settles on 1041's customer, and the agent replies to the wrong person. Nothing failed. Both requests returned 200. The request for 1041 hit a slow database query and finished second, and the component accepted whatever arrived last. On the developer's laptop, where the API answers in a few milliseconds and always in order, the bug never happened once.

The common misconception

The belief: loading data in React takes three steps. Start a fetch in useEffect, list the id in the dependency array so it fetches again when the id changes, and call setState when the response comes back. Add a loading flag and you're done.

It's half right, which is why it's so common. React's docs agree that an Effect is a reasonable place to fetch data that must match what's on screen: the data should follow the current id however it changed, whether by a click, a back button or a link. And the three-step version passes every demo, because local servers are fast and answer in order. What it misses is that the Effect runs once per id, so several requests can be in flight at once, and nothing in those three steps says which response still matters.

What actually happens

Requests don't finish in the order you send them

Each time ticketId changes, React runs the Effect again and a new request starts. The earlier request isn't cancelled: it's still on its way, and its .then callback will still call setTicket when it lands. Responses can come back in any order, depending on server load, caching and the network. React's docs use a search box as the example: type "hello" quickly and the response for "hell" can arrive after the one for "hello", so the screen shows results for a query the user no longer has. Two requests raced, and the wrong one finished last. That's a .

Cleanup tells an old request it's no longer wanted

An Effect can return an , and React calls it before running the Effect again with new dependencies, and once more when the component unmounts. React's docs say a fetching Effect's cleanup should either abort the fetch or ignore its result. Their version declares let ignore = false inside the Effect, checks if (!ignore) before setting state, and sets ignore = true in the cleanup. Every run of the Effect gets its own ignore variable, so when the id changes from 1041 to 1042, only the 1041 run is marked, and its late response is dropped.

An AbortController goes one step further. You pass its signal to fetch and call abort() in the cleanup, which can stop the request and the reading of its body. The catch is that an aborted fetch rejects with a DOMException named AbortError, so your error handling has to treat that as expected rather than as a failure:

TSX TicketDetails.tsx
import { useEffect, useState } from "react";export function TicketDetails({ ticketId }: { ticketId: string }) {  const [ticket, setTicket] = useState<Ticket | null>(null);  useEffect(() => {    // Whichever response arrives last wins    fetch(`/api/tickets/${ticketId}`)      .then((res) => res.json() as Promise<Ticket>)      .then(setTicket)      .catch(showError);  }, [ticketId]);  return ticket ? <TicketView ticket={ticket} /> : <Spinner />;}

Clicking from 1041 to 1042 now goes like this: React commits the new id, runs the 1041 cleanup, which aborts that request, then starts the fetch for 1042. Whatever the 1041 request does next, it can't touch state: either it rejects with an AbortError that the catch ignores, or it finds signal.aborted already true. The signal.aborted checks act as the ignore flag, so the code stays correct even if a response was already on its way when the user clicked.

One gap remains: until 1042 arrives, the panel still shows 1041. Render it as <TicketDetails key={ticketId} ticketId={ticketId} /> and each ticket starts from a fresh, empty state, as an earlier article showed.

ApproachA stale response…What else you get
fetch and setState, no cleanupCan overwrite newer dataNothing
An ignore flag set in cleanupIs ignoredWorks with any promise
AbortController aborted in cleanupIs ignored, with a check or a caught AbortErrorThe request stops if still running
Your framework's data fetching or a data libraryIs handled for youCaching, and no hand-written Effect

How to apply it in your project

  1. Find every fetch inside an EffectSearch useEffect bodies for fetch(, your API client, or any promise that ends in a state setter. Each one without a returned cleanup can show stale data.
  2. Add a cleanup that aborts or ignoresUse an AbortController when the call accepts a signal, and an ignore flag when it doesn't. Either way, check it before setting state.
  3. Treat AbortError as normalSkip error toasts, logs and retry logic for requests that were aborted on purpose, by checking signal.aborted or the error's name.
  4. Move fetching into one placeWrap the pattern in a useData(url) Hook, or adopt your framework's loaders or a data library, so components stop writing raw fetching Effects.

Key takeaways

  • Responses can arrive in any order, so a plain setState lets the slowest request win, not the newest one.
  • An Effect's cleanup runs before the next fetch and on unmount; use it to abort the old request or ignore its result.
  • An aborted fetch rejects with an AbortError; check signal.aborted and don't report it as a failure.
  • Two requests in development are Strict Mode testing your cleanup; for caching and server rendering, use a framework or a data library.

📚 المصادر

  1. Synchronizing with Effects — React
  2. You Might Not Need an Effect — React
  3. useEffect — React API Reference
  4. AbortController — MDN Web Docs
  5. Window: fetch() method — MDN Web Docs

التعليقات (0)