Fetching data

Topic 1 of 4 in Data fetching7 min readIntermediateFree course

Overview

Most React apps display data from a server: courses, users, comments. React itself doesn’t fetch data — you use the browser’s fetch (or a library) and put the result in state. This lesson shows how to do that correctly with effects, the pitfalls that catch everyone, and why most teams use a library instead.

A first version

JSX
function CourseList() {
  const [courses, setCourses] = useState([]);

  useEffect(() => {
    fetch('/api/courses')
      .then((res) => res.json())
      .then((data) => setCourses(data));
  }, []);

  return (
    <ul>
      {courses.map((c) => <li key={c.id}>{c.title}</li>)}
    </ul>
  );
}

It works on a good day. But it has no loading indicator, no error handling, and — as you’ll see — a race condition as soon as it depends on a prop.

Loading and error states

Users need to know when data is loading and when something went wrong. Track all three states:

JSX
function CourseList() {
  const [courses, setCourses] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch('/api/courses');
        if (!res.ok) throw new Error(`Request failed with status ${res.status}`);
        setCourses(await res.json());
      } catch (err) {
        setError(err);
      } finally {
        setIsLoading(false);
      }
    }
    load();
  }, []);

  if (isLoading) return <Spinner />;
  if (error) return <p role="alert">Couldn’t load courses. {error.message}</p>;
  if (courses.length === 0) return <p>No courses yet.</p>;

  return <ul>{courses.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}

Two details:

  • Check res.ok. fetch only rejects when the network fails. A 404 or 500 response resolves successfully, so you must throw for it yourself.
  • The effect function can’t be async (it must return a cleanup function or nothing, not a promise), so define an async function inside and call it.

Race conditions

Now the list depends on a search query:

JSX
useEffect(() => {
  fetch(`/api/courses?q=${query}`)
    .then((res) => res.json())
    .then(setResults);
}, [query]);

The user types “re”, then “rea”. Two requests go out. If the “re” request is slower, it arrives last and overwrites the correct “rea” results:

Two requests on a timeline. The fetch for “re” is slow, taking 900 ms; the fetch for “rea” starts later but takes only 300 ms. At 450 ms the “rea” results are shown correctly, but at 900 ms the “re” results arrive and overwrite them. The fix uses an ignore flag set to true in the effect’s cleanup, and only calls setResults if ignore is false.

Fix 1: ignore stale responses

Use the effect’s cleanup to mark old requests as stale:

JSX
useEffect(() => {
  let ignore = false;

  fetch(`/api/courses?q=${encodeURIComponent(query)}`)
    .then((res) => res.json())
    .then((data) => {
      if (!ignore) setResults(data);
    });

  return () => {
    ignore = true;
  };
}, [query]);

When query changes, React runs the cleanup for the previous effect before starting the next one, so the old request’s ignore becomes true and its result is dropped.

Fix 2: abort the request

Better still, cancel the old request so it doesn’t waste bandwidth, using an AbortController:

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

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

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

Aborting makes fetch reject with an AbortError, which you ignore — it isn’t a real failure.

Wrap it in a hook

All of this belongs in a custom hook, so components stay simple:

JSX
export function useFetchJson(url) {
  const [state, setState] = useState({ data: null, error: null, isLoading: true });

  useEffect(() => {
    const controller = new AbortController();
    setState({ data: null, error: null, isLoading: true });

    fetch(url, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`Request failed: ${res.status}`);
        return res.json();
      })
      .then((data) => setState({ data, error: null, isLoading: false }))
      .catch((error) => {
        if (error.name !== 'AbortError') setState({ data: null, error, isLoading: false });
      });

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

  return state;
}

// const { data: course, error, isLoading } = useFetchJson(`/api/courses/${id}`);

The limits of fetching in effects

Even with a perfect hook, effect-based fetching has real drawbacks:

  • No caching. Navigate away and back, and the data is fetched again, with another spinner.
  • No deduplication. Two components asking for the same data make two requests.
  • Waterfalls. A parent fetches, renders a child, which only then starts its own fetch. Requests that could run in parallel run one after another.
  • Late start. Effects run after rendering, so fetching can’t begin until the JavaScript has downloaded, run and painted.
  • No retries, no background refresh, no invalidation after you change data.

That’s why the React team recommends a data-fetching library or a framework:

Approach Good for
TanStack Query (next lessons) client-rendered apps: caching, deduplication, retries, mutations
React Router loaders loading data per route, in parallel, before rendering (see Route loaders and actions)
Frameworks with Server Components (Next.js) fetching on the server, close to the database (see Server components)

Understanding the manual version still matters: it’s what those tools do for you, and you’ll meet effect-based fetching in plenty of existing code.

Practical tips

  • Keep your API base URL in an environment variable: import.meta.env.VITE_API_URL.
  • Put fetch helpers in one module (api.js) that sets headers, parses JSON and throws on errors — every component benefits.
  • Encode user input in URLs with encodeURIComponent or URLSearchParams.
  • Show something useful while loading: a skeleton of the content is less jarring than a spinner.

In development, StrictMode runs your effect twice, so you’ll see two requests in the Network tab — the first one aborted. That’s expected and proves your cleanup works.

Exercise

A course detail fetcher

Write useCourse(id) that fetches /api/courses/${id} and returns { data, error, isLoading }. Handle non-OK responses as errors, ignore stale responses when id changes quickly, and abort the request on cleanup with an AbortController (ignore the resulting AbortError). Use it in CourseDetail({ id }) with a loading message, an error message and the course title.

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

export function useCourse(id) {
  // your code here
}

export function CourseDetail({ id }) {
  // your code here
}

Summary

  • Fetching in useEffect means tracking data, loading and error state yourself.
  • Check res.ok — fetch only rejects on network errors, not on 404 or 500 responses.
  • Responses can arrive out of order; ignore stale ones with a flag or abort them with AbortController in cleanup.
  • Effect-based fetching starts only after render and can create request waterfalls.
  • For real apps, use a data library (TanStack Query) or a framework’s loaders, which add caching, deduplication and retries.