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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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 theAbortErrorsilently. - 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
AbortErrorreaches your catch and may show an error message.Mistake: "
isMountedchecks are the fix"Fix: the problem happens while mounted, between two runs of the effect.
Easy to hard
Questions interviewers ask, easy to hard
- A user types "lap" then "laptop" and the "lap" response arrives last. How do you prevent it?
- AbortController vs an ignore flag: which is better and why?
- Combine it with debounce.
- What about requests that already reached the server?
- How do Suspense or a query library handle it?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.