Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 132 ยท Data and Async

Fetching Data

Fetch data in React with useEffect - loading, error and data states, race conditions, AbortController cleanup, StrictMode double requests, fetch pitfalls and when to use a library.

Almost every real interface shows data that lives somewhere else: a list of products, a user profile, search results. React itself has no opinion about where data comes from. A component renders from props and state; getting data into state is up to you. The classic way, still taught and still everywhere in existing code, is to fetch inside an effect: render once with nothing, start a request, and when the answer arrives put it in state and render again.

That pattern looks easy and hides a surprising number of traps: three states instead of one, requests that arrive in the wrong order, errors that fetch does not report, extra requests in development, and waterfalls that make pages slow. This lesson builds the pattern step by step, breaks it on purpose, fixes it, and ends with an honest look at where fetch-in-effect stops being a good idea. It assumes you know useState and useEffect, plus promises and async/await from the JavaScript lesson.

Our editor has no server and TryIt previews run in a sandbox without network access to your own API. So the examples use a simulated API (functions that return promises after a short timeout), plus real fetch calls to data: and Blob URLs, which behave like a tiny local server. The code you write around them is exactly what you would write against a real API.

The three states of a request

At any moment a request is in one of three situations: loading (waiting), success (we have data) or error (it failed). A component that fetches must render all three. A beginner usually writes this as separate variables; a clearer way is one status string plus the payload.

Here is the simulated API we will reuse. It resolves after a delay, rejects for unknown ids, and (importantly for later) listens to an AbortSignal.

JavaScript
const users = {
  1: { name: 'Ada Lovelace', role: 'Mathematician' },
  2: { name: 'Grace Hopper', role: 'Computer scientist' },
  3: { name: 'Linus Torvalds', role: 'Kernel maintainer' },
};

function fetchUser(id, { signal } = {}) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      if (users[id]) resolve(users[id]);
      else reject(new Error(`User ${id} was not found.`));
    }, 150);
    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new DOMException('The request was aborted.', 'AbortError'));
    });
  });
}

The first version fetches when the component appears and whenever userId changes:

Fetching in an effect: loading, error and data

Click through the buttons. Each click shows Loading user N... for 150 ms and then a card. User 99 does not exist, so the promise rejects and the .catch branch renders Error: User 99 was not found.. Follow what React does: the first render has status 'loading' and an effect scheduled; after the browser paints, the effect starts the request; when the promise settles, a state update triggers a second render with the data. Changing userId re-runs the effect because it is in the dependency array.

The component reads like a small state machine: if for each status, one return per case. That is a good habit, because it makes it impossible to read user.name while user is null.

The race condition

Look closely at what happens when the user clicks faster than the server answers. Request A starts; before it returns, the user changes the id and request B starts. Nothing guarantees that A returns before B. If A is slower, its answer arrives last and overwrites the correct data. The screen then shows a user that does not match the selected button.

Here is the bug, built deliberately. User 1 is slow (250 ms), user 2 is fast (50 ms), and the effect has no protection.

A race condition (fails on purpose)

Wait for the first answer (user 1 is selected at the start), press Pick 2 and let it finish, then press Pick 1 and, immediately after, Pick 2. The console shows the fast answer first and the slow one last: answer for 2 arrived: Grace (fast answer) followed by answer for 1 arrived: Ada (slow answer). The page ends at Selected: 2 | Showing: Ada (slow answer): it is lying. In production this bug appears only on slow connections, which is why it survives testing.

The fix: ignore stale answers, and abort the request

The effect's cleanup function runs before the next effect and when the component unmounts (useEffect explains the timing). We can use it to say "the request this effect started no longer matters". Two tools, usually combined:

  1. An ignore flag: the cleanup sets it to true, and the .then callback checks it before touching state. Works with any promise.
  2. An AbortController: the cleanup calls controller.abort(). Real fetch then stops the network request and rejects with an AbortError. Aborting saves bandwidth; the flag alone only discards the result.
Cleanup with AbortController

Select Pick 2 and wait for the card, then press Pick 1 and, before it finishes, Pick 2 again. The console shows request for 1 aborted, and the card for user 2 appears and stays. The order in which answers arrive no longer matters, because every effect run owns exactly one request and cancels it when it is replaced. Two details to copy: the AbortError is expected and must not be shown as an error; and the whole state is one object ({ status, user, message }), so impossible combinations such as "loading with an error" cannot exist.

Setting state at the start of an effect

You may have noticed setState({ status: 'loading' }) at the top of the effect. It works, and it is the usual teaching pattern, but it causes an extra render and linters in newer React setups flag synchronous state updates inside effects. The cleaner alternative is to derive loading: store the result together with the id it belongs to ({ id: 2, user }) and say const loading = result?.id !== userId. Either is acceptable; derived state has fewer moving parts once you are comfortable with it.

Real fetch has its own pitfalls

So far the API was simulated. fetch returns a promise of a Response, and its traps are different from what many people expect:

  • fetch does not reject on HTTP errors. A 404 or 500 still resolves. Check response.ok (or response.status) yourself and throw.
  • Reading the body is a second async step: await response.json() can fail too, if the server sends something that is not JSON.
  • Network failures reject with a TypeError (the message differs by browser).
  • Abort rejects with a DOMException named AbortError.

The following demo uses the real fetch, aimed at a data: URL (an inline JSON document, which acts as a server that always answers) and at a Response object we build ourselves to stand in for a 404.

Real fetch: ok, HTTP errors and bad JSON

Press each button. Good JSON prints the parsed object. HTTP 404 shows HTTP 404 failed -> Error: Server answered 404 Not Found: our own response.ok check turned it into an error, because fetch itself had resolved. Broken JSON fails in response.json() with a SyntaxError; the message wording depends on the browser. A small wrapper like loadJson is worth having in every project so that all three failure kinds reach your catch as ordinary errors.

Blob URLs work the same way: URL.createObjectURL(new Blob([json], { type: 'application/json' })) gives a blob: address that fetch can read, which is handy for tests and demos. A real app would call fetch('/api/users/' + id, { signal }) instead.

Extracting a reusable hook

Most components that fetch repeat the same state machine. Move it into a custom hook, and every component shrinks to a few lines. The hook below also adds a retry button by keeping a counter in the dependency array.

A useAsync hook with retry

The first call is built to fail (odd-numbered calls reject), so you see the error with a Try again button; pressing it increments attempt, the effect re-runs, and the second call succeeds with the list. The eslint-disable comment is honest: the hook's deps come from the caller, so the linter cannot verify them. That is one reason libraries exist, and the next sections explain more.

StrictMode and the double request

Wrap your app in <StrictMode> (every create-vite and Next.js app does) and React runs each effect twice on mount in development: it mounts, runs the cleanup, and mounts again, to check that your cleanup really undoes your setup. For a fetching effect this means two requests in development. That is not a bug in React; it is a test. A correct effect, one with an abort or ignore cleanup, behaves identically either way; production runs the effect once.

StrictMode starts the effect twice

The console reads: request 1 started, request 2 started, then request 1 was cancelled, result ignored and request 2 finished, and the page shows data from request 2. Mount, cleanup (which aborted request 1), mount again. If you "fix" the double request by adding a useRef guard that skips the second run, you hide the very check that protects you from stale data; keep the cleanup instead. Duplicate requests also disappear once a caching layer deduplicates them, as below.

Why fetch-in-effect has limits

The pattern works, and it is fine for a small app. But it has structural costs that grow with the product:

  • Waterfalls. The component must render before its effect starts the request, and a child component renders only after its parent. If Page fetches the user and then renders Posts, which fetches the posts, the second request starts only after the first finished plus a render. Two 150 ms requests take 300 ms instead of 150 ms.
  • No caching. Leave a page and come back and you wait again. Two components that need the same data each send a request.
  • Boilerplate you maintain. Loading, error, retry, abort, refetch on window focus, pagination, polling and updating after a mutation: each is more code in your effects.
  • Nothing on the server. Effects do not run during server rendering, so the first HTML a visitor receives is a loading spinner, which hurts speed and search ranking.

The demo below shows both the waterfall and the missing cache with a counter of requests. It uses the simulated API so numbers are predictable.

Two components, one resource, two requests

Both components show the same settings, yet the console logs request #1 for /settings and request #2 for /settings: each hook call sends its own request. At page scale that doubles server load for every shared resource.

A glimpse of the cure: caching shared requests

The smallest possible fix is a cache of promises keyed by what is being asked for. Whoever asks second gets the promise already in flight. Real libraries (below) do this with much more care, but the idea fits in a few lines:

A tiny request cache

Now the console shows a single request #1 for /settings, and both components get their data from it. What this toy cache lacks is the hard part: knowing when data is stale, refetching it, evicting old entries, handling failures (a rejected promise stays in the cache forever here), and updating the cache after a mutation. That is the job of a server-state library.

Server-state libraries and framework data loading

The community's answer to all of the above is to treat server data as its own kind of state, separate from UI state. TanStack Query (formerly React Query) and SWR give you caching, deduplication, background refetching, retries, pagination and mutations behind one hook. Routers such as React Router and Next.js go further and load data before rendering the page, which removes the waterfall. This is the read-only picture; none of it is installed in our editor, and it is covered in Caching and Server State.

JSX
// Read-only: needs "npm install @tanstack/react-query" and a QueryClientProvider.
import { useQuery } from '@tanstack/react-query';

function UserCard({ userId }) {
  const { data, isPending, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: ({ signal }) => fetch(`/api/users/${userId}`, { signal }).then((r) => r.json()),
  });

  if (isPending) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return <p>{data.name}</p>;
}

React 19 also adds the use hook, which reads a promise during rendering and works with Suspense for the loading state. It removes the three useState calls, but still needs a cache outside the component to be safe; see The use Hook and Suspense.

Which approach when?

Situation Reasonable choice
A prototype, one or two requests, a learning project fetch in useEffect with cleanup, as in this lesson
An app with many screens, shared data, mutations A server-state library such as TanStack Query or SWR
Server-rendered or file-routed app (Next.js, React Router framework mode) The framework's loaders or Server Components
Data that depends on a user action (submit, save) Form actions, not an effect

Do not fetch in effects for things that can be computed from props, and never fetch inside the render body: render must be pure.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a fetching component need three kinds of UI (loading, error, success)?

    Every request is in one of these states at any time. Rendering all of them prevents reading data that does not exist yet and shows the user what is going on.
  2. 2. What causes the race condition in a fetching effect without cleanup?

    Responses are not guaranteed to come back in the order requests were sent. Without cancelling or ignoring old requests, the last arrival wins even when it is outdated.
  3. 3. A server responds to fetch with status 404. What does the fetch promise do?

    fetch only rejects on network failure or abort. HTTP error statuses resolve, so you must check response.ok and throw yourself.
  4. 4. How should an AbortError from an aborted request be handled in the catch handler?

    Aborting is something your own cleanup does on purpose. Treating it as a failure would flash an error each time the user changes the input.
  5. 5. Why does a fetching effect run twice on mount in development with StrictMode?

    StrictMode tests that your effect can be torn down and set up again safely. With proper cleanup the extra run is harmless, and production only runs the effect once.

Summary

  • Fetching in an effect is a three-state machine: loading, success, error. Keep them in one state object.
  • Slow responses can arrive out of order. Clean up in the effect: set an ignore flag and call controller.abort().
  • Treat AbortError as expected, and never show it as a failure.
  • fetch resolves on HTTP errors: check response.ok, and remember response.json() can fail.
  • Extract the state machine into a custom hook such as useAsync, with a counter in the dependencies for retry.
  • StrictMode runs effects twice in development on purpose; keep the cleanup instead of guarding with a ref.
  • Fetch-in-effect causes waterfalls, duplicate requests and spinner-only server HTML; for real apps use a server-state library or framework data loading.

Next: The use Hook and Suspense