Skip to the page

Effects and synchronisation · senior

Fetching in effects and race conditions

When a fetch effect re-runs, an older slow response can arrive after a newer fast one and overwrite it; the effect cleanup must ignore or abort the old request, and debounce alone does not fix ordering.

The notes

What you must know

  • Bug: user types "lap" then "laptop"; the "lap" response arrives last and replaces the "laptop" results.
  • Fix A: let ignore = false; fetch(...).then(d => { if (!ignore) setResults(d) }); return () => { ignore = true; } (react.dev pattern).
  • Fix B: AbortController: const c = new AbortController(); fetch(url, { signal: c.signal }); return () => c.abort(); It also cancels the network request. Handle the AbortError silently.
  • Fix C outside effects: a request id / sequence number; only apply the response whose id is the latest.
  • Debounce reduces the number of requests; it does not guarantee order. Combine it with ignore/abort.
  • Abort does not undo work the server already did; for mutations use idempotency instead.
  • Production answer: a query library (TanStack Query, RTK Query) keys requests by the query key, dedupes and drops stale results; with Suspense, use() of a cached promise per key.
  • Also handle loading and error states, and do not set state after unmount (the cleanup handles that too).

The red pen

Common traps: mistake → fix

  • Mistake: "Debounce fixes the race"

    Fix: responses can still arrive out of order.

  • Mistake: "Aborting is enough" (without handling the rejection)

    Fix: the AbortError reaches your catch and may show an error message.

  • Mistake: "isMounted checks are the fix"

    Fix: the problem happens while mounted, between two runs of the effect.

Easy to hard

Questions interviewers ask, easy to hard

  1. A user types "lap" then "laptop" and the "lap" response arrives last. How do you prevent it?
  2. AbortController vs an ignore flag: which is better and why?
  3. Combine it with debounce.
  4. What about requests that already reached the server?
  5. How do Suspense or a query library handle it?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview