Skip to content
← Back to all articles
For Developers

How to Fix React API Race Conditions with AbortController

Modern React applications frequently communicate with APIs to display search results, product listings, dashboards and other dynamic information.

However, asynchronous requests do not always complete in the order they were initiated. When an older request finishes after a newer request, it can overwrite the latest application state and display incorrect information.

This is a common example of a React API race condition.

In this guide, we will explore why these problems occur and how to address them using AbortController, useEffect cleanup and guarded state updates.

1. What is an API race condition in React?

A race condition occurs when the correctness of an operation depends on the unpredictable timing of asynchronous events.

Consider a product search component.

A user initially searches for “r” and then quickly changes the search term to “react”.

The application sends two requests:

Imagine Request A takes 500 milliseconds to complete, while Request B starts 100 milliseconds later and takes only 100 milliseconds.

Request B finishes first and displays the correct results. Request A finishes later and replaces them with outdated results.

The input displays “react”, but the results correspond to “r”.

These timings are illustrative, not measured performance results.

2. The common React implementation that causes the problem

Consider this simplified search component:

useEffect(() => {
  async function loadResults() {
    const response = await fetch(
      "/api/search?q=" + encodeURIComponent(query)
    );

    if (!response.ok) {
      throw new Error("Search failed");
    }

    const data = await response.json();
    setResults(data);
  }

  loadResults().catch(setError);
}, [query]);

Every time the query changes, the effect starts another request.

The implementation does not cancel previous requests or check whether a response still belongs to the current query.

As a result, any completed request can update the component state, regardless of when it started.

3. What is AbortController?

AbortController is a standard Web API that allows supported asynchronous operations to be cancelled.

An AbortController provides an AbortSignal that can be passed to fetch.

const controller = new AbortController();

fetch("/api/products", {
  signal: controller.signal
});

// Cancel the request
controller.abort();

When the signal is aborted, fetch or ongoing response-body consumption can reject.

Cancellation is useful when a request is no longer relevant, such as when a user changes a search term or navigates away from a page.

However, aborting a client-side request does not guarantee that the server stops processing it.

4. Fix React API race conditions using useEffect cleanup

React effects can return cleanup functions.

When dependencies change, React runs the previous effect’s cleanup before setting up the replacement effect. Cleanup also runs when the component unmounts.

This makes effect cleanup a useful place to cancel obsolete requests.

Here is a more complete search hook:

import { useEffect, useState } from "react";

export function useSearch(query) {
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    const term = query.trim();

    if (!term) {
      setResults([]);
      setLoading(false);
      setError(null);
      return () => controller.abort();
    }

    async function search() {
      setLoading(true);
      setError(null);
      setResults([]);

      try {
        const response = await fetch(
          "/api/search?q=" +
            encodeURIComponent(term),
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Search request failed");
        }

        const data = await response.json();

        if (!controller.signal.aborted) {
          setResults(data);
        }
      } catch (err) {
        if (!controller.signal.aborted) {
          setError(err);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    search();

    return () => controller.abort();
  }, [query]);

  return { results, loading, error };
}

This example assumes the search API returns an array of results.

Each effect creates a new AbortController. When the query changes, the previous controller is aborted.

The signal checks also prevent an obsolete operation from committing its results, error or loading state after cancellation.

5. Using the custom search hook

The hook can be integrated into a reusable search component:

import { useState } from "react";
import { useSearch } from "./useSearch";

export default function SearchBox() {
  const [query, setQuery] = useState("");

  const { results, loading, error } =
    useSearch(query);

  return (
    <section>
      <label htmlFor="search">Search</label>

      <input
        id="search"
        value={query}
        onChange={e => setQuery(e.target.value)}
        placeholder="Search products"
      />

      {loading && <p>Searching...</p>}

      {error && (
        <p role="alert">{error.message}</p>
      )}

      <ul>
        {results.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </section>
  );
}

The example assumes each result has a unique id and a name.

For production applications, consider accessibility announcements, empty-result states, caching and appropriate loading indicators.

6. Debouncing vs AbortController

Debouncing and cancellation solve different problems.

Debouncing reduces unnecessary request starts

A debounce waits until the user stops typing for a configured duration before updating the search term.

For example, a 300-millisecond debounce can prevent requests from starting for every individual keystroke during rapid typing.

AbortController cancels obsolete requests

Cancellation addresses requests that have already started but are no longer needed.

Debouncing alone does not guarantee that responses arrive in the correct order. Two requests can still overlap when the user pauses and then continues typing.

A reliable search implementation can combine both approaches.

Implement a reusable debounce hook

import { useEffect, useState } from "react";

export function useDebouncedValue(value, delay) {
  const [debounced, setDebounced] =
    useState(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebounced(value);
    }, delay);

    return () => clearTimeout(timer);
  }, [value, delay]);

  return debounced;
}

Use the debounced value as the input to the search hook.

const debouncedQuery =
  useDebouncedValue(query, 300);

const { results, loading, error } =
  useSearch(debouncedQuery);

When using this approach, decide whether to display previous results during the debounce period or hide them until the new search starts.

7. What if an asynchronous operation cannot be cancelled?

Not every asynchronous operation supports AbortSignal.

For non-cancellable operations, another approach is to assign a unique identifier to each request and allow only the latest operation to update state.

const latestRequest = useRef(0);

async function search(term) {
  const requestId = ++latestRequest.current;

  const data = await searchService(term);

  if (requestId === latestRequest.current) {
    setResults(data);
  }
}

This pattern assumes useRef has been imported and the code runs inside a React component or custom hook.

In a complete implementation, guard error and loading updates as well, and invalidate outstanding identifiers when the component unmounts.

Request identifiers prevent stale commits, but they do not stop unnecessary network or server work.

8. Testing API race conditions

Race conditions can be difficult to reproduce when testing only against fast local APIs.

Create deterministic tests that control when asynchronous requests complete.

A useful test scenario is:

  1. Start search A.
  2. Start search B.
  3. Resolve search B first.
  4. Verify that B’s results are displayed.
  5. Resolve search A afterward.
  6. Verify that B’s results remain visible.

Also test cancellation, empty search terms, HTTP errors, rapid input changes and component unmounting.

Browser DevTools network throttling can help reproduce timing-related issues manually, but deterministic mocked responses are generally better for automated regression tests.

9. Common mistakes to avoid

Frequently Asked Questions

Does AbortController work with React?

Yes. AbortController is a browser API that can be used inside React components and custom hooks.

Can AbortController cancel a completed request?

It cannot undo a completed operation or reverse server-side changes. It can signal cancellation to supported ongoing operations.

Is AbortController better than debouncing?

Neither replaces the other. Debouncing reduces request starts, while cancellation helps manage obsolete requests that have already started.

Does React Strict Mode affect API requests?

In development, Strict Mode can perform an additional effect setup and cleanup cycle to help identify incorrect cleanup logic. Effects should be designed to handle this behavior.

Can TanStack Query help with request cancellation?

Yes. TanStack Query provides an AbortSignal to query functions. Consuming that signal in the underlying request enables cancellation behavior. Query keys and caching also help organize server state.

Conclusion

React API race conditions are a correctness problem that can appear whenever multiple asynchronous operations overlap.

Using AbortController with effect cleanup and guarded state updates helps prevent obsolete responses from overwriting newer application state.

Combine cancellation with debouncing when appropriate, handle errors carefully and test requests that complete out of order.

Reliable frontend engineering is not only about making applications faster. It is also about ensuring they display the correct information under unpredictable network conditions.

Need help debugging React applications, optimizing API integrations or implementing reliable frontend architecture? Connect with Tekody for professional remote engineering and AI development support.

👉 Request Support: https://tekody.com/get-support/

📲 WhatsApp for Support: +91-8527854783

Need help with a similar challenge?

Discuss your requirements with Tekody and explore practical support options.