DEV Community

Cover image for Understanding Race Conditions in React: When API Responses Arrive Out of Order
Sneha Kumari
Sneha Kumari

Posted on

Understanding Race Conditions in React: When API Responses Arrive Out of Order

While learning React and API integration, I came across an interesting problem called a race condition.

At first, it sounded like a complicated concept. But I realised it can happen in a simple React application too.

Imagine a clinical trial search page

Suppose you're building a feature in an application like MedMatch, where users can search for clinical trials.

A user types:

  1. Cancer — the application sends Request A.
  2. Before the first response arrives, the user types Breast Cancer — Request B is sent.
  3. Request B finishes first and displays its results.
  4. Request A finishes later and overwrites those results.

Now the search field says "Breast Cancer", but the results belong to "Cancer".

That's a race condition!

Why does this happen?

API requests are asynchronous. This means:

  • Multiple requests can run at the same time.
  • Each request can take a different amount of time.
  • Responses don't always arrive in the order they were sent.

As a result, an older response can overwrite newer data in the UI.

How can we handle it?

One approach is using JavaScript's AbortController.

It allows us to cancel an earlier fetch request when the search query changes.

useEffect(() => {
  const controller = new AbortController();

  async function fetchTrials() {
    try {
      const response = await fetch(
        `/api/trials?q=${query}`,
        { signal: controller.signal }
      );

      const data = await response.json();

      if (!controller.signal.aborted) {
        setResults(data);
      }
    } catch (error) {
      if (error.name !== "AbortError") {
        console.error(error);
      }
    }
  }

  fetchTrials();

  return () => controller.abort();
}, [query]);
Enter fullscreen mode Exit fullscreen mode

What's happening here?

  • AbortController creates a cancellation controller.
  • Its signal is passed to fetch().
  • When the query changes, React runs the previous effect's cleanup.
  • The previous request is aborted if it is still in progress.
  • Before updating the UI, we check whether the request was aborted.

The final check is useful because a request can be aborted even after its response headers arrive, while the response body is still being read.

Two more techniques worth knowing

AbortController isn't the only tool developers use.

1. Debouncing

Instead of sending an API request after every keystroke, we wait for the user to stop typing for around 300–500 milliseconds.

This reduces unnecessary API calls.

2. Data-fetching libraries

Libraries such as:

  • TanStack Query (React Query)
  • SWR

provide features like caching, request deduplication, and handling asynchronous server state. They can simplify many data-fetching problems, although correct query keys and cancellation behaviour still matter.

My takeaway

Earlier, I thought API integration was mainly about sending requests and displaying responses.

Now I understand that handling asynchronous behaviour is equally important. We also need to think about request timing, stale data, loading states, and error handling.

It's a small detail, but it can make a real difference to the user experience.

I'm still learning React, one concept at a time.

Have you encountered race conditions while working with API calls in React? How did you handle them?

Top comments (27)

Collapse
 
dafili profile image
Renhua Wei •

{ signal: controller.signal } stops the stale write, but it does not bind the array to the query that produced it: anything downstream that renders query directly - the "27 trials" count, a chart title, the aria-live announcement - can still paint Breast Cancer next to Cancer's array for a frame, and abort only closes that window when the request is slower than the repaint. I keep { q, items } as one state object and read the label off state.q, so a late response can only ever repaint a self-consistent pair and abort degrades to a bandwidth optimization instead of the correctness guarantee. On React 18 with automatic batching, are your count and list updated in the same setResults call, or does the badge read from the input?

Collapse
 
sneha_kumari profile image
Sneha Kumari •

That's a really good point! In my example, the query comes from the input while the list and count come from the fetched results, so they could briefly get out of sync. Keeping { q, items } together in one state object is a much safer approach because the displayed label and data stay connected. I hadn't considered that part of the problem. Thanks for bringing it up!

Collapse
 
dafili profile image
Renhua Wei •

Batching doesn't close it: React 18 collapses the setState calls inside one handler, but your badge and your list come from different sources, so they diverge across the network boundary, not within a tick. Cheapest fix is deleting the count state - render items.length and read the label from state.q, so there's one value that cannot disagree with itself. If you can't delete it yet, guard the write instead: drop the response when response.q !== state.q and there's no frame where the old label sits next to the new array.

Thread Thread
 
sneha_kumari profile image
Sneha Kumari •

Ah, I see what you mean now! The mismatch happens across the network boundary, not because React is rendering the state updates separately. Deriving the count from items.length and the label from state.q also avoids maintaining duplicate state. That's a much cleaner approach. Thanks for explaining this!

Thread Thread
 
dafili profile image
Renhua Wei •

Right - and the part that still needs a test is the ordering, not the derivation: fire two mocked responses out of order (slow "breast" resolving after fast "cancer") and assert the final label and count both come from the same one. If you keep the abort, also assert the aborted request never calls setState - a spy on setState is enough, and it catches the case where the abort fires after the response already landed.

Thread Thread
 
sneha_kumari profile image
Sneha Kumari •

That's a good point! I was focusing more on keeping the query and results consistent, but testing the actual response order is just as important. Mocking two requests with different response times would be a good way to verify that the older response never overwrites the newer one. I hadn't thought of testing the abort behaviour separately too. Thanks for suggesting this!

Thread Thread
 
dafili profile image
Renhua Wei •

Deferreds beat timers for this: const d = new Map(); const req = (q) => new Promise((r) => d.set(q, r));, fire q1 and q2, then resolve d.get('q2')() first and d.get('q1')() after - the order itself becomes the assertion instead of a sleep. The part worth asserting separately is the intermediate paint: wrap each resolve in await act(async () => ...) and check the label and the count right after the first resolve, not only at the end.

Thread Thread
 
sneha_kumari profile image
Sneha Kumari •

I see why you would prefer deferred promises here. With timers, we are only assuming that one request will finish before the other, but with deferreds, we explicitly control the resolution order. The intermediate assertion is what I find particularly important. If q2 resolves first, the UI should show q2's results, and even after q1 resolves later, the query label and result count should remain consistent with q2. Otherwise, checking only the final state could hide the race condition. I'd also test the abort behaviour independently to make sure the outdated request is actually cancelled, rather than just prevented from updating the UI.

Thread Thread
 
dafili profile image
Renhua Wei •

The abort test usually passes for the wrong reason: once await res.json() has resolved, controller.abort() is a no-op - the body is already consumed, so nothing rejects and "cancelled" is really only asserting the state guard. Move the abort before the body read and have the mock reject only while signal.aborted is true, then expect(p).rejects.toMatchObject({ name: 'AbortError' }) - a broken abort path then shows up as a hang instead of a green test.

Thread Thread
 
sneha_kumari profile image
Sneha Kumari •

Oh, that's a really good catch! I was treating the state guard and actual request cancellation as almost the same thing, but they're not. If the body is already consumed, the abort test could pass without really testing cancellation. Moving the abort before the body read makes much more sense. Definitely something I need to revisit in my tests. Thanks for pointing that out!

Collapse
 
smtahosin profile image
S M Tahosin • • Edited

The problematic part for me was not the search itself, it was the details page where one could navigate through the items fast enough to make data from the previous item appear briefly. The final aborted check is much more important than it might seem for you, because aborting a fetch request does not necessarily stop work that is already finished on the server or in the promise chain that has not received any signals to abort. In my case, the simple guard by request id where only the latest id can set state, and handling the AbortError silently without indicating failure to load at all, that is what helped me. The StrictMode double invocation of effects in development was also useful for me, as the race showed up on my machine instead of only in production.

Collapse
 
sneha_kumari profile image
Sneha Kumari •

That's a really good point! I mostly thought about this issue with search, but the details page example makes it even clearer. I also didn't know StrictMode could help catch these issues so easily. Thanks for sharing your experience!😊

Collapse
 
smtahosin profile image
S M Tahosin • • Edited

Good thing the details page one worked, I was missing that one for years as I was just playing around with search all the time. The request id guard was the boring part that saved the day, as abort by itself caused some renders to be done after some time even when the chain did not propagate the signal. StrictMode catching it on the local machine is actually great.

Thread Thread
 
sneha_kumari profile image
Sneha Kumari •

Haha, true! It's always better to catch these issues during development than hear about them from users later. I hadn't thought of using a request ID as a backup. Definitely something I'll keep in mind. Thanks for sharing your experience!

Thread Thread
 
smtahosin profile image
S M Tahosin • • Edited

Anytime. Glad the request id guard worked for me on that details page, it has earned its place there. Hope the fix works well in your app also.

Collapse
 
melnykk profile image
Artem Melnyk •

Your search example made this click for me. I have seen the same thing in a search box. You type more, the old results show up late, and the page looks wrong. I had not thought about the cleanup part of useEffect before. Cancelling the old request when the query changes is a simple fix. I will try AbortController first, then look at debouncing. Have you tried it on a details page too, where you click through items fast?

Collapse
 
sneha_kumari profile image
Sneha Kumari •

I haven't tried it on a details page yet, but now I'm curious to test that too! I can see how quickly clicking between items could cause the same issue. Definitely adding this to my list of things to explore.

Collapse
 
melnykk profile image
Artem Melnyk •

Nice, let me know what you find. The details page version is sneaky because it looks right most of the time. It only breaks when you click fast. A request id check helped me think about it. The last request wins, and the older ones get ignored.

Thread Thread
 
sneha_kumari profile image
Sneha Kumari •

Ohh, that makes sense! It probably goes unnoticed during normal testing since everything looks fine until you click really fast. I'll definitely try this on my MedMatch details page. The request ID approach is something I'll keep in mind. Thanks for explaining it!

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

Request B finishes first, Request A lands later and the screen says Breast Cancer with Cancer results. Aborting helps, but the check before setResults is what keeps a late body from overwriting the screen.

Collapse
 
sneha_kumari profile image
Sneha Kumari •

Exactly! That's what I found interesting too. I initially thought cancelling the request was enough, but that final check is an important extra safety step. It's a small detail, but it can prevent some really confusing UI issues. Thanks for adding this!

Collapse
 
sherotree profile image
Sherotree •

That post-json() aborted check is the part most AbortController examples skip, and it's the one that actually loses the race when the body is still streaming. I'd still debounce the search before you fetch, though — otherwise every keystroke cancels a request the server already started, and you pay for work the UI never uses.

Collapse
 
sneha_kumari profile image
Sneha Kumari •

That's a good point! Debouncing before fetching helps avoid sending a request for every keystroke, while the abort check protects against stale responses. I think using both together makes the search flow much more efficient and reliable. Thanks for pointing that out!

Collapse
 
argumentmoney8117 profile image
ArgumentMoney8117 •

The post-json() abort check was the part I had not seen in most AbortController examples. Checking signal.aborted after the body is parsed is a small addition, but it is what keeps a cancelled request from being treated as a successful update.

Collapse
 
sneha_kumari profile image
Sneha Kumari •

Yess, exactly! I almost missed that detail myself at first. It's a small check, but it can save you from some confusing bugs later. Glad you found it useful!

Collapse
 
syedfahads profile image
Syed Fahad •

small gotcha with the debounce option: it makes the race rarer but doesn't fix it. two requests 400ms apart can still come back in the wrong order, so keep the abort too

Collapse
 
sneha_kumari profile image
Sneha Kumari •

Debouncing reduces how often requests are sent, but it doesn't guarantee they'll finish in the same order. Keeping AbortController alongside it is important to handle that. Thanks for pointing out this distinction!