MyInternships.in

Data Fetching & APIs

React AbortController and Race Conditions

A race condition happens when a slower earlier request resolves after a faster later one and overwrites fresh data with stale data. AbortController cancels the outdated request in the effect cleanup so this cannot happen.


What is AbortController and Race Conditions in React?

A race condition happens when a slower earlier request resolves after a faster later one and overwrites fresh data with stale data. AbortController cancels the outdated request in the effect cleanup so this cannot happen.

Why AbortController and Race Conditions matters

Type quickly into a search box and several requests are in flight at once. Without cancellation the results you see may correspond to a query you already replaced.

AbortController and Race Conditions example

Cancelling on every dependency change
JSX
useEffect(() => {
  const controller = new AbortController();

  fetch(`/api/search?q=${query}`, { signal: controller.signal })
    .then(r => r.json())
    .then(setResults)
    .catch(err => { if (err.name !== 'AbortError') setError(err); });

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

How this works

React runs the cleanup before re-running the effect, so each new keystroke aborts the previous request. Only the newest response can ever reach setResults.

The ignore-flag alternative

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

This does not cancel the network request but does prevent a stale response from updating state — useful when the API client has no abort support.

Key points to remember

  • Ignore AbortError in the catch; it is expected, not a failure.
  • Axios accepts the same signal option.
  • Debouncing reduces requests; aborting fixes ordering. Serious search UIs use both.

React AbortController and Race Conditions— Interview Questions & FAQs

Why do my search results flicker between old and new values?+

An earlier, slower request resolved after a later one. Abort the previous request in the effect cleanup so only the newest response can update state.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships