Fetching data
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
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:
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.fetchonly 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:
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:
Fix 1: ignore stale responses
Use the effect’s cleanup to mark old requests as stale:
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:
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:
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
encodeURIComponentorURLSearchParams. - 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.
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.
import { useEffect, useState } from 'react';
export function useCourse(id) {
// your code here
}
export function CourseDetail({ id }) {
// your code here
}import { useEffect, useState } from 'react';
export function useCourse(id) {
const [state, setState] = useState({ data: null, error: null, isLoading: true });
useEffect(() => {
const controller = new AbortController();
setState({ data: null, error: null, isLoading: true });
fetch(`/api/courses/${id}`, { 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') return; // a newer request replaced this one
setState({ data: null, error, isLoading: false });
});
return () => controller.abort();
}, [id]);
return state;
}
export function CourseDetail({ id }) {
const { data, error, isLoading } = useCourse(id);
if (isLoading) return <p>Loading course…</p>;
if (error) return <p role="alert">Couldn’t load the course: {error.message}</p>;
return <h1>{data.title}</h1>;
}Summary
- Fetching in
useEffectmeans tracking data, loading and error state yourself. - Check
res.ok—fetchonly 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
AbortControllerin 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.