← Back to React, page 2

react-0030 · Medium mid

How do you fetch data in useEffect safely, and how do you avoid race conditions?

Start the request inside the effect, store the result in state, and return a cleanup function that cancels the request with an AbortController (or marks it as ignored). Without cleanup, a slow response for an old id can arrive after a fast response for a new id and overwrite it. Handle loading and error states too. For real apps, a data library or framework loader is usually better than hand-written effects.

Full answer

A basic effect fetch looks simple: when userId changes, call the API and set the result. The problem is ordering. Imagine the user goes from id 1 to id 2 quickly. Request 1 is slow, request 2 is fast. Request 2 finishes and shows user 2, then request 1 finishes and replaces it with user 1. The screen now says user 1 while the page title says user 2. This is a race condition.

The fix lives in the effect's cleanup. When userId changes, React runs the previous cleanup before the new effect. If the cleanup aborts the previous request, its result is never applied. With fetch, pass { signal: controller.signal } and call controller.abort() in the cleanup. Ignore the resulting AbortError, because it is expected. A simpler, older version uses a local let ignore = false flag that the cleanup sets to true, and the callback checks before calling setState.

A solid effect also handles the other states: loading while waiting, error when the request fails (check response.ok, since fetch does not reject on a 404), and reset of old data when the id changes. Another clean route is to give the component a key, such as key={userId}, so each id gets fresh state.

In development, StrictMode runs the effect twice, so you will see two requests. The cleanup cancels the first. This is intentional and not a bug in your code.

Effects have limits for data work. They run only on the client, after the first paint, which delays data, and you must write caching, retries and deduplication yourself. Libraries such as TanStack Query and SWR solve these, and frameworks load data in route loaders or Server Components. In React 19, the use API with Suspense is the built-in way to read a promise during render.

The example uses a simulated request so it can run without a network. It rejects with an AbortError when cancelled, as fetch does.

jsx
import { useEffect, useState } from 'react';

function fakeFetchUser(id, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve({ id, name: 'User ' + id }), 100);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new DOMException('Aborted', 'AbortError'));
    });
  });
}

function UserCard({ userId }) {
  const [state, setState] = useState({ status: 'loading', user: null });

  useEffect(() => {
    const controller = new AbortController();
    setState({ status: 'loading', user: null });

    fakeFetchUser(userId, controller.signal)
      .then((user) => setState({ status: 'done', user }))
      .catch((error) => {
        if (error.name === 'AbortError') {
          console.log('request for user ' + userId + ' was cancelled');
        } else {
          setState({ status: 'error', user: null });
        }
      });

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

  if (state.status === 'loading') return <p>Loading user {userId}...</p>;
  if (state.status === 'error') return <p>Could not load user.</p>;
  return <p>{state.user.name}</p>;
}

export default function App() {
  const [userId, setUserId] = useState(1);
  return (
    <div>
      <button onClick={() => setUserId((id) => id + 1)}>Next user</button>
      <UserCard userId={userId} />
    </div>
  );
}

The check pressed Next user twice before any request finished. The first two requests were cancelled and only user 3 was shown. Output of the run: request for user 1 was cancelled request for user 2 was cancelled Final markup: <div><button>Next user</button><p>User 3</p></div>

Key points

  • Out-of-order responses cause race conditions when a dependency changes quickly.
  • Cancel the old request in the effect cleanup with AbortController, or ignore its result with a flag.
  • Handle loading, error and non-OK responses. fetch does not reject on a 404.
  • StrictMode double requests in development are expected, not a bug.
  • Prefer a data library, route loader or Server Components for real applications.

Common mistakes

  • Skipping cleanup, so a slow old response overwrites a newer one.
  • Making the effect callback async directly. Define an inner async function and call it.
  • Treating a 404 or 500 as success because fetch resolved.
  • Forgetting to reset or show loading state when the id changes.
  • Fetching in an effect for data that a framework loader or a server component could provide earlier.

Follow-ups

  • How would the same fetch look with the use API and Suspense?
  • What does a library such as TanStack Query add over a hand-written effect?
  • How do you avoid a request waterfall between parent and child components?

Tips

  • Describe the failure first (slow response 1 beats fast response 2). It proves you understand the race.
  • Show AbortController, then say what you would use in production. Interviewers like candidates who know the limits of effects.
  • Mention the StrictMode double call before they ask.