Skip to main content

React Data Fetching Without Race Conditions: AbortController in useEffect

The naive effect left User 1 on screen after userId flipped from 1 (80 ms) to 2 (10 ms). The same test with AbortController showed User 2 and aborted 1 of 2 requests.

Updated 11 min readMarkdown
Part of seriesFrontend
React Data Fetching Without Race Conditions: AbortController in useEffect

I wrote a Vitest test that says: if userId changes from 1 to 2, the profile on screen should be user 2. I rendered the naive useEffect fetch, waited until both requests had finished, and asserted /User 2:/. It failed. The DOM still had user 1. Pasted from the run on 20 Nov 2026, 08:25 IST:

 FAIL  src/naive-latest-should-fail.test.jsx > shows the user for the latest id after both fetches settle (expected to FAIL on NaiveUserProfile)
TestingLibraryElementError: Unable to find an element with the text: /User 2:/.

<body>
  <div>
    <p>
      User
      1
      :
      User 1
    </p>
  </div>
</body>

User 1's response was set to arrive in 80 ms, user 2's in 10 ms. The late response won. I then ran the same sequence against an effect that passes an AbortController signal to fetch and aborts it in the cleanup function. The UI showed user 2, and the mock recorded 1 abort out of 2 starts. Every count below is from that run.

[race] naive  userId 1 (80 ms) then 2 (10 ms) -> UI "User 1: User 1", started=2, completed=2, aborted=0
[race] safe   userId 1 (80 ms) then 2 (10 ms) -> UI "User 2: User 2", started=2, completed=1, aborted=1
[strict] safe userId 7, StrictMode -> UI "User 7: User 7", started=2, completed=1, aborted=1
[strict] naive userId 7, StrictMode -> UI "User 7: User 7", started=2, completed=2, aborted=0

The 80 ms and 10 ms figures are delays I set in the fake fetch so the race is deterministic. They are not production measurements. The start / abort / complete counts are what the mock recorded.

Most articles on this topic show the AbortController snippet and stop. Almost none ship a test that fails on the naive effect and passes on the fix, and almost none count what React StrictMode does to the same fetch. That's the gap this post fills.

The short version

  • A useEffect that fetches on userId and always calls setUser will apply whichever response finishes last, not which request was started last.
  • findByText(/User 2/) can pass at 10 ms, while the 80 ms response is still in flight, and hide the race. The failing test waits until both fetches have settled (stats.completed === 2) and then asserts the latest id.
  • The fix is the cleanup function: create an AbortController for each effect run, pass signal to fetch, call controller.abort() on cleanup, and ignore a result that still arrives (for work that does not honor the signal). Treat AbortError as expected, not as a UI error.
  • In the run, the safe effect showed user 2 and aborted 1 of 2 requests. The naive effect completed both and showed user 1.
  • React StrictMode in development mounts, unmounts, and remounts the effect. With abort, that was started=2, aborted=1, completed=1. Without abort, both runs completed (completed=2). The UI happened to be right because both responses were for user 7. You still paid for two completions, and a slower first run would have been a race against itself.
sequenceDiagram
    participant UI
    participant Effect as useEffect
    participant Net as fetch
    UI->>Effect: userId=1
    Effect->>Net: GET /users/1 (80 ms)
    UI->>Effect: userId=2, run cleanup
    Effect->>Net: abort /users/1
    Effect->>Net: GET /users/2 (10 ms)
    Net-->>Effect: user 2
    Effect->>UI: setUser(user 2)
    Note over Net: /users/1 never calls setUser

What the top results cover, and what they skip

I read the top results for "react useeffect abortcontroller race condition" on 20 Nov 2026:

Result Good at Missing
Max Rozen: Fixing Race Conditions in React with useEffect The canonical write-up: ignore flag vs AbortController, a demo with a random delay No automated test. The delay is random, so you can't assert "the late response lost".
Mironsoft: Avoiding Race Conditions in useEffect with AbortController Clear abort-vs-ignore comparison, AbortError filtering, shared signals Snippets only. No failing test, no StrictMode counts.
React Lab: Effect Cleanup and AbortController Ties cleanup of a connection to cleanup of a fetch, with a good stale-setState explanation An exercise, not a test that fails first.
React Performance: Canceling Requests Bandwidth and waterfall view of cancelled requests No RTL/Vitest test for the stale-user assertion.
React docs: useEffect Official cleanup rules and the development double-invoke under StrictMode Shows the ignore-flag pattern more than a fetch abort, and does not ship a race test.

The gap is a small repo where one test fails on the naive effect after both responses settle, the same assertion passes with AbortController, and a StrictMode test counts aborted requests. That's this post.

Setup

What Value
Runtime Node v24.22.1
UI React 19.3.1
Tests Vitest 3.2.7, Testing Library 16.3.3, jsdom 27.4.0
Fake network installFakeFetch({ delays: { 1: 80, 2: 10, 7: 20 } }), honors AbortSignal
Run it ./run.sh in the project folder (one expected failure, then 4 passing tests)

The fake fetch looks up the id at the end of the URL, waits that many milliseconds, then resolves with { id, name: "User " + id }. If the signal aborts, it clears the timer, increments aborted, and rejects with a DOMException named AbortError.

1. The naive effect, and a test that actually waits

useEffect(() => {
  setUser(null);
  setError(null);
  fetch(`/api/users/${userId}`)
    .then((res) => {
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res.json();
    })
    .then((data) => setUser(data))
    .catch((err) => setError(err.message));
}, [userId]);

There is no cleanup. When userId changes, React runs the effect again, but the first fetch is still in flight. Its then will call setUser whenever it finishes.

This is the assertion I wanted to hold:

test("shows the user for the latest id after both fetches settle", async () => {
  const { rerender } = render(<NaiveUserProfile userId={1} />);
  rerender(<NaiveUserProfile userId={2} />);
  await waitFor(() => {
    expect(stats.completed).toBe(2);
  }, { timeout: 400 });
  expect(screen.getByText(/User 2:/)).toBeInTheDocument();
  expect(screen.queryByText(/User 1:/)).not.toBeInTheDocument();
});

The important line is stats.completed === 2. If I had only written await screen.findByText(/User 2:/), the test would have passed at about 10 ms, then the 80 ms response would have overwritten the UI after the test had already finished. I confirmed that: the same assertion without waiting for both completions passed against the naive component in 29 ms. Waiting for both completions is what made it fail, at 113 ms, with user 1 still on screen.

A characterization test in the passing suite records the bug on purpose:

[race] naive  userId 1 (80 ms) then 2 (10 ms) -> UI "User 1: User 1", started=2, completed=2, aborted=0

Two starts, two completions, zero aborts, stale user.

2. Abort in cleanup, and ignore anything that still arrives

useEffect(() => {
  const controller = new AbortController();
  let ignore = false;
  setUser(null);
  setError(null);

  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then((res) => {
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res.json();
    })
    .then((data) => {
      if (!ignore) setUser(data);
    })
    .catch((err) => {
      if (err.name === "AbortError" || ignore) return;
      setError(err.message);
    });

  return () => {
    ignore = true;
    controller.abort();
  };
}, [userId]);

AbortController is what actually cancels the in-flight request. The ignore flag is the backup for work that does not take a signal (a hand-rolled client, a JSON parse that already started, a library that swallows the signal). React runs this cleanup before the next effect, and on unmount, so a stale then should not write.

Do not show AbortError in the UI. It is the cleanup doing its job. In the run, the same latest-id sequence against this component showed user 2:

[race] safe   userId 1 (80 ms) then 2 (10 ms) -> UI "User 2: User 2", started=2, completed=1, aborted=1

Two starts, one completion, one abort. The 80 ms request never reached setUser.

3. StrictMode is the same race, against yourself

In development, React StrictMode runs effects twice: setup, cleanup, setup. If the fetch has no cleanup, you start two requests for the same userId. In the run, the naive profile still showed user 7, and the mock recorded started=2, completed=2, aborted=0. Both responses were for user 7, so the UI looked fine. If the first run were slower than the second, you would have the same stale-setState bug with a single id.

With abort, the first run is cancelled by the StrictMode cleanup:

[strict] safe userId 7, StrictMode -> UI "User 7: User 7", started=2, completed=1, aborted=1

That is the behaviour you want in development, and it is the same cleanup that protects you when the prop actually changes in production. StrictMode does not run this double-invoke in production builds; the test still matters because it proves the cleanup is wired up.

The run

Pasted from RESULTS.txt, 20 Nov 2026, 08:25 IST. Node v24.22.1, Vitest 3.2.7, React 19.3.1, Testing Library 16.3.3, jsdom 27.4.0.

----- expected FAIL: naive component, assert latest id wins after both fetches settle -----
 FAIL  src/naive-latest-should-fail.test.jsx > shows the user for the latest id after both fetches settle (expected to FAIL on NaiveUserProfile)
TestingLibraryElementError: Unable to find an element with the text: /User 2:/.
<body>
  <div>
    <p>User 1: User 1</p>
  </div>
</body>
 Test Files  1 failed (1)
      Tests  1 failed (1)

----- expected PASS: characterization + safe component -----
[race] naive  userId 1 (80 ms) then 2 (10 ms) -> UI "User 1: User 1", started=2, completed=2, aborted=0
[race] safe   userId 1 (80 ms) then 2 (10 ms) -> UI "User 2: User 2", started=2, completed=1, aborted=1
[strict] safe userId 7, StrictMode -> UI "User 7: User 7", started=2, completed=1, aborted=1
[strict] naive userId 7, StrictMode -> UI "User 7: User 7", started=2, completed=2, aborted=0
 Test Files  1 passed (1)
      Tests  4 passed (4)

Checklist

  • Fetch inside useEffect only when the request is tied to a reactive value (userId, a query, a room id).
  • Create a new AbortController at the start of each effect run and pass signal to fetch.
  • Abort in the cleanup function. Set an ignore flag too, for work that does not honor the signal.
  • Ignore AbortError. Surface real HTTP and network errors.
  • Write a test that waits until every started request has settled, not just until the latest user first appears.
  • Run the same component under <StrictMode> and count aborts. If completed equals started in development, cleanup is not wired.

Interview follow-ups

"Can't I just ignore the result with a boolean and leave the request running?" Yes, and that prevents the stale setState. It does not cancel the request, so you still pay for the bandwidth and for any server work. AbortController does both. I use both: abort first, ignore as a backstop.

"What if I await the fetch and the component unmounts?" The promise rejects with AbortError (or you check ignore after await). Either way, don't call setState and don't set an error banner.

"Does this replace a request library?" No. TanStack Query, SWR and friends handle cancellation, caching and retries for you. This post is the pattern you need when you are writing the useEffect, and the test you'd want around it.

"Why did findByText(/User 2/) pass on the buggy component?" Because user 2 arrived first. The test ended at 29 ms; user 1 arrived at 80 ms and overwrote the UI afterwards. A race test has to wait for the slow request too.

"StrictMode showed the right user without abort. So I'm fine?" You were lucky that both responses were for the same id. Change userId quickly, or let the first StrictMode run finish later than the second, and the naive effect has the same bug.

Sources

Written by Gowtham M. Code tested on Node v24.22.1 / React 19.3.1 / Vitest 3.2.7 / Testing Library 16.3.3 / jsdom 27.4.0, 20 Nov 2026.

No comments yet. Be the first to comment.

Frontend

Part 1 of 1

Tested React and frontend patterns: real code, real test output.