
Fetching in useEffect Has a Race Condition You Haven't Noticed
- كاتب موثّق
- React 19
محتويات المقال
The common misconception
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.
What actually happens
Requests don't finish in the order you send them
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
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.
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:
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 />;}import { useEffect, useState } from "react";export function TicketDetails({ ticketId }: { ticketId: string }) { const [ticket, setTicket] = useState<Ticket | null>(null); useEffect(() => { const controller = new AbortController(); const { signal } = controller; fetch(`/api/tickets/${ticketId}`, { signal }) .then((res) => res.json() as Promise<Ticket>) .then((data) => { if (!signal.aborted) setTicket(data); // only the current run }) .catch((err: unknown) => { if (!signal.aborted) showError(err); // AbortError is expected }); return () => controller.abort(); // before the next ticket's fetch }, [ticketId]); return ticket ? <TicketView ticket={ticket} /> : <Spinner />;}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.
<TicketDetails key={ticketId} ticketId={ticketId} /> and each ticket starts from a fresh, empty state, as an earlier article showed.
fetch and setState, no cleanup | ||
ignore flag set in cleanup | ||
AbortController aborted in cleanup | AbortError | |
How to apply it in your project
Find every fetch inside an Effect Search useEffectbodies forfetch(, your API client, or any promise that ends in a state setter. Each one without a returned cleanup can show stale data.Add a cleanup that aborts or ignores Use an AbortControllerwhen the call accepts asignal, and anignoreflag when it doesn't. Either way, check it before setting state.Treat AbortError as normal Skip error toasts, logs and retry logic for requests that were aborted on purpose, by checking signal.abortedor the error's name.Move fetching into one place Wrap 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 setStatelets 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 fetchrejects with anAbortError; checksignal.abortedand 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.
التعليقات (0)