DEV Community

forqx
forqx

Posted on Originally published at diffdojo.com

A React code review exercise about race conditions, with a solution

A race condition in a React component usually looks like this in a diff: a useEffect starts a fetch whenever a prop or state value changes, and nothing cancels or ignores the request that is already in flight. If the older response arrives last, it overwrites the newer one, and the screen shows data for a query the user has already replaced. This post is a code review exercise on that bug: an eleven-line search component, then the review comment, the fix and a test.

In 2022, someone filed a bug against Material UI's Autocomplete: during fast typing the input would randomly reset, flash "no results," then settle on the wrong suggestions. The root cause was async responses arriving out of order, with the stale one quietly overwriting the fresh one. jQuery UI's autocomplete had the same class of bug open for years. I have shipped this bug myself. Every frontend developer I know who has built a search box has shipped it at least once, because it is invisible on a fast office connection, impossible to reproduce on purpose unless you already know the cause, and the code that produces it looks completely correct.

The exercise below is built around that pattern. If you are practicing React or JavaScript pull request review, or you want a reflex for catching async bugs in AI-generated code before they ship, read the PR, decide on a verdict, and then compare it with the walkthrough.

The requirements

The PR description says:

Adds live user search. The component fetches /api/search whenever the query changes and renders the matching users. Tested locally with several queries and the list updates correctly on every keystroke.

The actual requirements are short:

  1. Add a live search box.
  2. As the user types, show the results that match the current query.
  3. The displayed list must always correspond to the latest query the user typed.

Context from the ticket: this is used in the admin panel header. Production users often search from slow mobile networks.

The PR

src/components/UserSearch.jsx

function UserSearch({ query }) {
  const [results, setResults] = useState([]);
  useEffect(() => {
    fetch(`/api/search?q=${query}`)
      .then((res) => res.json())
      .then((data) => setResults(data));
  }, [query]);
  return (
    <ul>{results.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

Eleven lines, new file, no deletions. The component takes query as a prop, fetches on every change, renders the result list. The author says it works locally. It does work locally. That is part of the problem.

Try it yourself first. The same PR is in DiffDojo with no spoilers: leave inline comments and a verdict, then come back for the walkthrough. Review this PR. A free account unlocks 1 PR of your choice; the pass opens the full library.


Where the race condition is

Start from what the code actually does when a user types "al" and then immediately types "alice". Two things happen in sequence: the effect fires for "al", starting a fetch, and then the effect fires again for "alice", starting a second fetch. Both are now in flight. Neither knows the other exists.

On the developer's office wifi, both responses come back in under 50 milliseconds, in order, and the UI looks perfect. But the requirements say this component lives in the admin panel header and production users search from slow mobile networks. On a congested 3G connection, the "al" request might take 800ms and the "alice" request might take 200ms (maybe it hits a cache, maybe the server is just faster for that particular query). Now "alice" resolves first and the UI correctly shows Alice. Then, 600 milliseconds later, "al" resolves and setResults(data) runs again, overwriting the screen with every user whose name contains "al": Alice, Alfred, Alejandra, Albert. The user is staring at the name "alice" in the search box and a list that does not match it. Requirement three is broken: the displayed list does not correspond to the latest query.

The ugly part is that no error fires. No test fails. No console warning appears. The component did exactly what the code says: it called setResults every time a response came back. The code just never bothered to ask whether the response was still relevant.

The review comment and the verdict

  useEffect(() => {
    fetch(`/api/search?q=${query}`)
      .then((res) => res.json())
      .then((data) => setResults(data));
  }, [query]);
Enter fullscreen mode Exit fullscreen mode

Review comment: Race condition: when the user types fast (or the network is slow), an older response can land after a newer one and overwrite the current results. The effect has no cleanup, so nothing cancels or ignores the stale fetch. On a slow mobile network, typing "al" then "alice" can show "al" results under the "alice" query. Add a cleanup function that sets an ignore flag, or use an AbortController to cancel the previous request.

The verdict is Request changes. This is not a style nit or an edge case that might hypothetically matter someday. The requirements explicitly say the displayed list must always correspond to the latest query, and this code cannot guarantee that. On the networks the component is designed to run on, it will regularly show stale results with no indication that anything went wrong.

The fix: ignore the stale response, or abort it

The simplest fix is the ignore flag pattern that the React docs recommend for exactly this situation. When the effect re-runs (because query changed), the cleanup function from the previous run sets ignore = true, and the old .then callback checks the flag before calling setResults:

  useEffect(() => {
    let ignore = false;
    fetch(`/api/search?q=${query}`)
      .then((res) => res.json())
      .then((data) => { if (!ignore) setResults(data); });
    return () => { ignore = true; };
  }, [query]);
Enter fullscreen mode Exit fullscreen mode

That is three lines added to the original code. The closure captures ignore while it is false. If query changes before the fetch completes, the cleanup runs, ignore becomes true, and when the stale response finally arrives, setResults never fires. The new, current fetch has its own ignore variable that is still false, so it updates the UI normally.

You could also use an AbortController, which actually cancels the HTTP request rather than just ignoring its result:

  useEffect(() => {
    const ctrl = new AbortController();
    fetch(`/api/search?q=${query}`, { signal: ctrl.signal })
      .then((res) => res.json())
      .then((data) => setResults(data))
      .catch((e) => { if (e.name !== 'AbortError') throw e; });
    return () => ctrl.abort();
  }, [query]);
Enter fullscreen mode Exit fullscreen mode

The AbortController version is slightly better in production because it tells the browser to drop the connection, saving bandwidth on mobile. Both versions solve the race condition. The ignore flag is the minimum viable fix; the abort is the production-grade one. Either is a valid request in review.

A test that catches the race condition

The trick to testing a race condition is controlling the order responses resolve. You cannot prove the bug exists by firing one request and checking the result, because the bug only manifests when two requests overlap. Here is a minimal test that breaks on the original code and passes on the fix:

let resolvers = {};
global.fetch = (url) => new Promise((resolve) => {
  const q = new URL(url, 'http://x').searchParams.get('q');
  resolvers[q] = (data) =>
    resolve({ json: () => Promise.resolve(data) });
});

// Render with query="al", then re-render with query="alice"
render(<UserSearch query="al" />);
render(<UserSearch query="alice" />);

// Resolve "alice" FIRST, then "al" SECOND
await act(() => resolvers['alice']([{ id: 1, name: 'Alice' }]));
await act(() => resolvers['al']([
  { id: 1, name: 'Alice' }, { id: 2, name: 'Alfred' }
]));

// The UI should show only Alice, not Alice + Alfred
expect(screen.getAllByRole('listitem')).toHaveLength(1);
expect(screen.getByText('Alice')).toBeInTheDocument();
Enter fullscreen mode Exit fullscreen mode

The key is the two act calls near the end: the "alice" response resolves first, and then the "al" response resolves second, simulating the exact out-of-order arrival that happens on a slow network. On the original code, after both resolve, the screen shows both Alice and Alfred (the "al" results), because the last setResults call wins regardless of which query it belongs to. The length assertion fails: expected 1 item, got 2. On the fixed code, the "al" callback checks ignore, finds it true, and skips the update. Only Alice remains on screen. The test passes.

Notice what the test does not do: it does not fire a single request and check whether the right data appeared. That test passes on the buggy code too, because single requests always work. The only way to catch this bug is to put two requests in flight and resolve them in the wrong order.

What this bug looks like in production

The ticket says this component lives in the admin panel header, used for looking up users. Think about a customer support agent searching for "John Smith" to issue a refund. They type "john", pause, then type "john smith". If "john" is slow and "john smith" is fast, the screen briefly shows John Smith, then silently replaces it with every John in the database. The support agent clicks the first result, which is now John Martinez, and refunds the wrong customer. There is no error in the logs, no failed assertion, nothing but a confused customer calling back to ask why they got a mysterious refund and John Smith still waiting.

The reason this bug class survives code review so well is that it requires the reviewer to simulate time. The code, read line by line, is correct: it fetches, it parses, it updates state, it depends on the right variable. You have to hold two copies of the effect in your head, running concurrently, and ask yourself what happens when one finishes before the other in the wrong order. Most reviews do not do that. Most reviews read the code like a single thread of execution, top to bottom, and this code reads perfectly in that mode.

The same race outside React, and when it is a security bug

The pattern is not specific to React or to the browser. In 2024 Raymond Chen walked through it in a native Windows autocomplete, where a slow lookup for an older query finishes after the lookup for a newer one and the window ends up showing results for text the user has already changed. His one-line statement of the problem fits this PR as written: "There is a race condition here if a newer autocomplete result completes more quickly than an older one."

It stops being a display glitch when the late response carries more than a list. In January 2026 the Turbo maintainers published a security advisory (CVE-2025-66803) for the same shape of bug: a Turbo Frame request still in flight during logout could come back afterwards with a Set-Cookie header reflecting the session as it was when the request started, restoring a session the user had just ended. The advisory rates it low severity and limits it to applications that keep sessions in client-side cookies. The fix in Turbo 8.0.21 is the one from this review: cancel the requests that are still in flight.

So when you find an uncancelled request in a review, look at what its response is allowed to change. A list of search results is the mild case. If the response can write a session, a token, the selected account or a form the user is about to submit, the same missing cleanup is a security finding, and the comment should say so.

The review habit: check every effect that fetches

Any time you see a fetch (or any async call) inside a useEffect, and the effect has no cleanup function, stop and ask: what happens when two of these are in flight at the same time? That single question catches this entire class of bug. It does not require you to be an expert on AbortController or to have memorized the React docs on data fetching. It just requires you to notice the missing cleanup and wonder what it is supposed to be cleaning up.

The pattern generalizes beyond search. Profile pages that fetch by user ID, dashboards that reload on tab change, chat rooms that load history by room ID: any component where a prop drives a fetch and the user can change that prop faster than the network can respond. The question is always the same: is there a guard against the stale response?

Common questions

Is there a React code review exercise about race conditions with a solution?

Yes, this post is one. The pull request adds a search component whose useEffect fetches on every query change and never cancels or ignores the previous request, so an older response can overwrite a newer one. The solution is in this post: the review comment, the verdict (request changes), two fixes and a test that fails on the original code. The same PR is in DiffDojo if you want to review it yourself before reading the answer.

How do I spot a race condition in a React pull request?

Look for an effect that starts an async call and has no cleanup function. Then ask what happens when two of those calls are in flight and the first one finishes last. If nothing cancels the earlier request or ignores its result, the stale response wins and the UI shows data for a value the user has already changed. The same check applies to any component where a prop or state value drives a fetch: search boxes, profile pages loaded by id, dashboards that reload on tab change.

How do I check that the fix removes the race condition?

Write a test that controls the order in which responses resolve. Start two requests, resolve the newer one first and the older one second, then assert that the screen still shows the newer result. The original code fails that test, and both the ignore flag and the AbortController version pass it. A test that fires a single request proves nothing, because a single request always works.

Where can I practice catching race conditions in code review?

DiffDojo has this PR and other React and Node pull requests with planted concurrency bugs, plus clean ones where the right call is to approve. You leave inline comments, give a verdict and get graded against a canonical review. One PR in every stack is open without signup, a free account opens one more of your choice, and the pass opens the rest of the library.

Related walkthroughs: a React stale closure in an interval, a correct PR that reviewers reject, forEach with an async callback.


Originally published on DiffDojo. DiffDojo is a trainer for reviewing AI-written pull requests: pick a PR and review it cold. One PR in every stack is free, no signup; a free account unlocks one more, and the pass opens the whole library.

Top comments (0)