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

  1. Race conditions: typing "re" then "react" fires two requests; if "re" answers last, its results overwrite "react".
  2. 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).
  3. Stale closures: a callback after await reads old state; setItems([...items, x]) loses concurrent updates.
  4. Strict Mode double effects: effects that start requests run twice in development; without cleanup you get duplicate requests or duplicated data.
  5. Double submits: users click twice before the first request finishes.
  6. Unhandled errors: rejected promises in effects or handlers that never show feedback.
  7. Async in useEffect directly: useEffect(async () => ...) returns a promise instead of a cleanup function.

Fixes

  • AbortController per request, aborted in cleanup.
  • let ignore = false in effects, set to true in cleanup.
  • Functional state updates after await.
  • Disable buttons while pending (useTransition, useActionState's isPending).
  • try/catch with 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";
2
3export function SearchResults({ query }: { query: string }) {
4 const [results, setResults] = useState<string[]>([]);
5 const [error, setError] = useState<string | null>(null);
6
7 useEffect(() => {
8 // useEffect(async () => ...) would be a bug: effects must return a cleanup, not a promise
9 const controller = new AbortController();
10
11 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 requests
19 }
20 }
21 run();
22 return () => controller.abort(); // a newer query (or unmount) cancels the old request
23 }, [query]);
24
25 return error ? <p role="alert">{error}</p> : <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;
26}
27
28export 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 submit
31}

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.

Open in study app