ReactMedium
Async bugs in React?
Async bugs in React usually come from work that finishes after the component's situation has changed: responses arriving out of order (race conditions), updates after unmount or after the user navigated, stale values captured by closures, double execution in Strict Mode, and unhandled promise rejections. Fix them with cancellation (AbortController), ignore flags, functional updates, proper cleanup, and data libraries that handle these cases.
Common bugs
- Race conditions: typing "re" then "react" fires two requests; if "re" answers last, its results overwrite "react".
- Updates after unmount or navigation: a slow request finishes and sets state on a screen the user left (React 18 removed the warning, but the work is wasted and can show wrong data).
- Stale closures: a callback after
awaitreads old state;setItems([...items, x])loses concurrent updates. - Strict Mode double effects: effects that start requests run twice in development; without cleanup you get duplicate requests or duplicated data.
- Double submits: users click twice before the first request finishes.
- Unhandled errors: rejected promises in effects or handlers that never show feedback.
- Async in
useEffectdirectly:useEffect(async () => ...)returns a promise instead of a cleanup function.
Fixes
AbortControllerper request, aborted in cleanup.let ignore = falsein effects, set totruein cleanup.- Functional state updates after
await. - Disable buttons while pending (
useTransition,useActionState'sisPending). try/catchwith user-visible errors; error boundaries for Actions and Suspense.- Define an inner async function in effects.
- Prefer TanStack Query, SWR or route loaders, which cancel, deduplicate and order requests for you.
Code example
tsx
1import { useEffect, useState, useTransition } from "react";23export function SearchResults({ query }: { query: string }) {4 const [results, setResults] = useState<string[]>([]);5 const [error, setError] = useState<string | null>(null);67 useEffect(() => {8 // useEffect(async () => ...) would be a bug: effects must return a cleanup, not a promise9 const controller = new AbortController();1011 async function run() {12 try {13 setError(null);14 const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal });15 if (!res.ok) throw new Error(`HTTP ${res.status}`);16 setResults(await res.json());17 } catch (e) {18 if ((e as Error).name !== "AbortError") setError((e as Error).message); // ignore cancelled requests19 }20 }21 run();22 return () => controller.abort(); // a newer query (or unmount) cancels the old request23 }, [query]);2425 return error ? <p role="alert">{error}</p> : <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;26}2728export function SaveButton({ save }: { save: () => Promise<void> }) {29 const [pending, start] = useTransition();30 return <button disabled={pending} onClick={() => start(save)}>{pending ? "Saving…" : "Save"}</button>; // no double submit31}
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.