Fetching Data in React
Fetching API data with useEffect, handling loading and error states, and data libraries.
What you'll learn
- The basic pattern for fetching data in useEffect
- Managing loading, success, and error states
- Preventing race conditions with cleanup flags
- When to use data-fetching libraries like React Query
Concept
The Basic Fetch Pattern
The most common way to fetch data in a React component is inside a useEffect that runs when the component mounts or when a relevant dependency changes. You call fetch() (or axios, or any HTTP client), parse the response, and update state with the result. The effect's dependency array typically includes the URL or parameters that determine what data to fetch.
Loading and Error States
A data fetch has three possible outcomes: loading (in progress), success (data received), or error (request failed). You need state for all three. A common pattern is three separate state variables: const [data, setData] = useState(null), const [loading, setLoading] = useState(true), and const [error, setError] = useState(null). Set loading to true before the fetch, set it to false after, and set either data or error depending on the outcome. Show a spinner while loading, the data on success, and an error message on failure.
Preventing Race Conditions
If the dependency that triggers the fetch changes while a previous fetch is still in flight, you have a race condition — the older response might arrive after the newer one and overwrite the correct data. Two solutions: use a cancelled flag in the cleanup function (set it to true, and check before setting state), or use an AbortController to actually cancel the in-flight request. The AbortController approach is cleaner because it cancels the network request entirely.
Data-Fetching Libraries
For production applications, consider a data-fetching library like TanStack Query (React Query) or SWR. These libraries handle caching, deduplication, background refetching, optimistic updates, and race conditions automatically. They also provide loading and error states out of the box. For simple one-off fetches, the manual useEffect pattern is fine, but for apps with many data dependencies, a dedicated library dramatically reduces boilerplate and improves UX.
Example
import { useState, useEffect } from "react";
function UserList() {
const [users, setUsers] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// AbortController cancels the request if the component unmounts.
const controller = new AbortController();
async function fetchUsers() {
try {
setLoading(true);
setError(null);
const res = await fetch("/api/users", { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") setError(err.message);
} finally {
setLoading(false);
}
}
fetchUsers();
return () => controller.abort(); // Cancel on unmount.
}, []);
if (loading) return <p>Loading users...</p>;
if (error) return <p className="error">Error: {error}</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name} — {u.email}</li>)}
</ul>
);
}
AbortController cancels the fetch on unmount, preventing state updates on an unmounted component. Three states handle loading, error, and success.
Try it
- HTTP Status Codes
Understand HTTP status codes returned by your API endpoints.
- JSON Formatter
Format and inspect the JSON data returned by your API calls.
Common mistakes
The mistake
Not handling the loading and error states
The fix
Every fetch has three outcomes: loading, success, error. Track all three in state. Show a spinner while loading and an error message on failure. Never assume the fetch always succeeds.
The mistake
Updating state after the component unmounts
The fix
Use an AbortController or a cancelled flag in the effect cleanup. Without this, a slow response arriving after unmount causes a 'state update on unmounted component' warning.
Practice Fetching Data in React
1 exercise
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.