Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 132 ยท Data and Async

Async Patterns and Race Conditions

Fix out-of-order responses and learn cancellation, debouncing, pagination, retry with backoff, timeouts and optimistic updates with rollback in React, with live examples.

Asynchronous code has a property that synchronous code lacks: you do not control the order in which things finish. You start request A, then request B, and B might come back first. The user clicks Save twice. The network drops halfway. A component unmounts while its request is still running. None of these are exotic: they happen to every app with real users on real networks.

This lesson is a tour of the patterns that make async UI correct. We start with the most important bug, the race condition, reproduce it on purpose, and fix it. Then we add debouncing, pagination, retries, timeouts and optimistic updates. All the "servers" below are simulated with timers, so every example runs in the editor.

Race conditions: out-of-order responses

Imagine a search box. Typing a starts request 1. Typing b makes the text ab and starts request 2. If request 1 happens to be slow and request 2 is fast, the responses arrive as 2, then 1. The effect that handles request 1 finally calls setResults with data for a, overwriting the correct results for ab. The input says ab, the list says a, and nothing looks broken in the code.

Here is that bug, built to be reproducible: the request for a takes 250 ms and the one for ab takes 50 ms.

A race condition (fails on purpose)

Press the button. Right away the page shows Input says: ab and List says: Results for "ab", which is correct. About 200 ms later the console logs response arrived for "ab" first and response arrived for "a" second, and the page flips to List says: Results for "a" while the input still says ab. That is the bug, visible on screen: the slow, old response won.

The bug is not that the request for a ran. It is that nobody told its callback "you are no longer wanted". The same effect closure still holds a setResult and will happily call it.

Fix 1: ignore stale results

The effect cleanup from Effect Cleanup is exactly the right tool. Each effect run gets its own ignore flag. When the query changes, React runs the previous cleanup, which flips the flag, so the old callback does nothing.

JSX
useEffect(() => {
  let ignore = false;
  searchApi(query).then((data) => {
    if (!ignore) {
      setResult(data);
    }
  });
  return () => {
    ignore = true;
  };
}, [query]);

This guarantees correctness: only the latest effect run may write state. The old request still travels the network and uses bandwidth, though.

Fix 2: cancel with AbortController

AbortController goes one step further and tells the work to stop. Real fetch accepts { signal } and rejects with an AbortError when aborted. We build the same contract into our fake API so you can run it:

Cancelling with AbortController

Press the button. This time the list ends on Results for "ab" and stays there. The console shows request for "a" was cancelled and then response arrived for "ab"; the response for a never arrives, because aborting cleared its timer. The cleanup controller.abort() runs when the effect re-runs for the new query, so every request is cancelled exactly when it becomes irrelevant.

Two rules to remember with AbortController:

  1. Aborted is not failed. An AbortError is a normal event in a UI. Never show it to the user as an error.
  2. A cancelled fetch does not undo what the server did. For writes (POST), aborting only stops waiting. Combine it with idempotency keys on the server if duplicates would hurt.

If you use a query library or use with a cached promise, the race is handled for you: each key has its own entry, so a late answer for a lands in the a entry, not in what you are looking at. See Caching and Server State.

Debouncing: do not search on every keystroke

Even with correct handling, sending a request per letter is wasteful. Debouncing waits until the user pauses: every new change restarts a timer, and only when the timer survives does the work happen. A tiny hook turns any value into a debounced value:

A useDebouncedValue hook

Type three letters quickly (we entered a, ab, abc in quick succession). Typed: follows every keystroke, but Debounced: stays empty until you pause for 400 ms and then jumps straight to abc. The console shows exactly one line, request sent: "abc"; without debouncing there would have been three.

Choose the delay by feel: 200 to 400 ms is typical for search. Debouncing is not a replacement for ignoring stale results: a slow response can still arrive late, so keep both. For rendering-heavy work that is not about the network, useDeferredValue is a better fit because it adapts to the device instead of waiting a fixed time.

Pagination and "load more"

Lists from servers arrive in pages. A cursor (or page number) identifies where the next page starts. The state you need is small: the items so far, the next cursor, and whether a request is running. The common bugs are double-loading (clicking twice fires two requests for the same page) and replacing instead of appending.

Load more with a guard

Click Load more three times, waiting for each page. The console shows request: items from 0, request: items from 4 and request: items from 8, the page text goes Loaded 4 of 11, Loaded 8 of 11 and Loaded 11 of 11, and the button becomes a disabled No more items. The last page holds only three items, and nextCursor becomes null, which is how the server says "that was the end". Because items are appended with a functional update, earlier pages are never lost.

Infinite scroll is the same thing with a different trigger: instead of a button, an invisible sentinel element at the bottom calls loadMore when it scrolls into view, using IntersectionObserver. The browser does the geometry for you; no scroll listeners are needed. This is a read-only sketch of the trigger:

JSX
function useOnVisible(callback) {
  const ref = useRef(null);
  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) callback();
    });
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, [callback]);
  return ref;
}

// <li ref={sentinelRef} aria-hidden="true" />   placed after the last item

Keep the guard from the example (isLoading), keep a visible "Load more" button for keyboard and screen reader users, and for very long lists combine this with virtualization.

Retry with backoff, and timeouts

Some failures are temporary: a 503, a dropped connection. Retrying helps, but retrying immediately in a tight loop hammers a struggling server. Exponential backoff waits longer after each failure (for example 40 ms, 80 ms, 160 ms; real apps use hundreds of milliseconds up to seconds, usually with random jitter so that thousands of clients do not retry in lockstep). Only retry errors that can change: network failures and 5xx responses, never a 400 or 404.

A timeout is the other side: a request that never answers must not keep the UI loading forever. Promise.race between your work and a timer is the simplest implementation.

Retry with backoff and a timeout

Press Load flaky data. The console shows attempt 1 failed (503 Service Unavailable), retrying in 40 ms and attempt 2 failed (503 Service Unavailable), retrying in 80 ms, then the page shows Data after 3 attempts. Press Load with timeout: after 100 ms the page shows Failed: Timed out after 100 ms.

Two caveats. Promise.race stops waiting but does not stop the work; to really cancel, pass an AbortSignal (in modern browsers AbortSignal.timeout(ms) creates one that aborts itself). And never retry a non-idempotent write blindly: a retried "charge the card" may charge twice unless the server deduplicates.

Optimistic updates and conflicts

Waiting for the server before updating the screen makes every click feel slow. An optimistic update assumes success: change the UI immediately, send the request, and roll back if it fails. It suits actions that almost always succeed, such as likes, toggles and reordering. React 19 has a dedicated hook for it, useOptimistic, covered in useFormStatus and Optimistic UI. Here is the manual version, because it shows what the hook automates and exposes the conflict problem.

The hard part is concurrent actions. If the user clicks twice and the first request fails, restoring a saved snapshot of the count (setLikes(previous)) would erase the second like too. Undo exactly your own change with a functional update instead.

Optimistic like with rollback

Click Like once: the count jumps to 11 immediately. After about 300 ms the first server call (which we made fail) is rejected, the count goes back to 10 and the message Could not save a like: Network error appears. The console shows server call 1 will fail. Now click twice in a row, before the first call finishes: the count shows 12, then, when call 1 fails, it drops to 11 (the second like survives) and call 2 succeeds (server call 2 will succeed). We tested that by clicking twice in the same tick and got a final Like (11) with the error message shown.

The pattern in four steps: apply the change locally, send the request, on success keep it (optionally replace with the server's authoritative value), on failure undo only your change and tell the user. For data that other people can change at the same time, also revalidate after the request, as in Caching and Server State, so the screen converges on what the server really holds.

A checklist for async UI

  • Out-of-order responses: ignore or abort stale work in the effect cleanup.
  • Unmount: cleanup also covers components that disappear mid-request.
  • Double submission: disable the button or guard with a flag while a request runs.
  • Loading and error states: every async path needs both, plus an empty state.
  • Idempotency: make retried writes safe on the server.
  • Timeouts and retries: bounded, with backoff, only for retryable errors.
  • Optimistic updates: roll back precisely, then revalidate.
  • Avoid effects for events: if work is the direct result of a click, do it in the handler (see You Might Not Need an Effect).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a search box show results for an older query?

    Requests are independent. If an older one finishes last, its callback still calls setState unless you ignore or abort it.
  2. 2. What is the cleanest way to stop an old request from updating state?

    The cleanup of the previous effect run executes before the next run, so it can mark the old work as unwanted.
  3. 3. What should you do with an AbortError caught from a cancelled fetch?

    An aborted request is intentional, not a failure. Only unexpected errors should reach the user.
  4. 4. What does debouncing a search value do?

    Each change restarts the timer; only a value that survives the whole delay is used, which avoids a request per keystroke.
  5. 5. Two optimistic likes are in flight and the first fails. Why is setLikes(count => count - 1) safer than restoring a saved number?

    A snapshot taken before the first click would also erase the second like. A functional update undoes only your own change.

Summary

  • Responses can arrive in any order; an old request must not overwrite newer state. Fix it with an ignore flag or AbortController in the effect cleanup.
  • An AbortError is expected and not a user-facing failure; aborting does not undo server-side effects.
  • Debounce input before searching, and still guard against stale responses.
  • For pagination keep items, the next cursor and an isLoading guard; infinite scroll is the same code triggered by IntersectionObserver.
  • Retry only retryable errors, with exponential backoff, and bound waiting with a timeout.
  • Optimistic updates change the UI first and undo precisely on failure; revalidate afterwards.

Next: Rendering in Depth