React Data Fetching
Most apps load data from a server: products, messages, search results. React doesn't include a fetching tool — you use the browser's fetch (or a library) and store the result in state. The tricky part isn't the request itself but the states around it: loading, success, error, and outdated responses.
Note: The playgrounds run in a sandboxed frame, so the examples simulate a server with Promises and
setTimeout. ReplacefakeApi(...)withfetch(url).then(r => r.json())in a real project — the React code stays the same.
The basic pattern
A component that loads data on mount needs three pieces of state and one effect:
import { useEffect, useState } from 'react';
const USERS = [
{ id: 1, name: 'Ngoc Anh', email: 'anh@example.com' },
{ id: 2, name: 'Quoc Bao', email: 'bao@example.com' },
{ id: 3, name: 'Thu Ha', email: 'ha@example.com' },
];
function fakeApi() {
return new Promise((resolve) => setTimeout(() => resolve(USERS), 1200));
}
export default function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fakeApi()
.then((data) => setUsers(data))
.catch((err) => setError(err))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>⏳ Loading users…</p>;
if (error) return <p style={{ color: 'crimson' }}>Error: {error.message}</p>;
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name} — <a href={`mailto:${u.email}`}>{u.email}</a></li>
))}
</ul>
);
}With real fetch, remember that an HTTP error (404, 500) does not reject the promise. Check response.ok yourself:
const res = await fetch('/api/users');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();async/await inside an effect
The effect function itself can't be async (it must return nothing or a cleanup function), so define an async function inside and call it:
import { useEffect, useState } from 'react';
function fakeWeather(city) {
return new Promise((resolve, reject) =>
setTimeout(() => {
if (city === 'Atlantis') reject(new Error(`City "${city}" not found`));
else resolve({ city, temp: 20 + city.length, sky: city.length % 2 ? '☀️' : '🌧️' });
}, 700)
);
}
export default function App() {
const [city, setCity] = useState('Hanoi');
const [state, setState] = useState({ status: 'loading' });
useEffect(() => {
let ignore = false;
async function load() {
setState({ status: 'loading' });
try {
const data = await fakeWeather(city);
if (!ignore) setState({ status: 'success', data });
} catch (err) {
if (!ignore) setState({ status: 'error', message: err.message });
}
}
load();
return () => { ignore = true; };
}, [city]);
return (
<div>
{['Hanoi', 'Singapore', 'Atlantis'].map((c) => (
<button key={c} onClick={() => setCity(c)} disabled={c === city} style={{ marginRight: 4 }}>{c}</button>
))}
{state.status === 'loading' && <p>Loading {city}…</p>}
{state.status === 'error' && <p style={{ color: 'crimson' }}>⚠️ {state.message}</p>}
{state.status === 'success' && <p style={{ fontSize: 22 }}>{state.data.sky} {state.data.city}: {state.data.temp}°C</p>}
</div>
);
}Storing a single state object with a status field makes impossible combinations (loading and error at once) impossible.
Race conditions and cancellation
If the user switches quickly, an older, slower response may arrive after a newer one. The ignore flag in the cleanup prevents it from overwriting the newer data. With real fetch you can also abort the request using an AbortController:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${query}`, { signal: controller.signal })
.then((r) => r.json())
.then(setResults)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => controller.abort();
}, [query]);Search with loading indicator
Putting it together: a debounced search where outdated responses are ignored and the previous results stay visible while new ones load:
import { useEffect, useState } from 'react';
const BOOKS = ['Clean Code', 'Code Complete', 'Design Patterns', 'Eloquent JavaScript', 'Learning React', 'Refactoring', 'The Pragmatic Programmer', "You Don't Know JS"];
function searchBooks(q) {
const delay = 300 + (q.length % 3) * 400; // responses arrive in unpredictable order
return new Promise((resolve) => setTimeout(() => resolve(BOOKS.filter((b) => b.toLowerCase().includes(q.toLowerCase()))), delay));
}
export default function App() {
const [query, setQuery] = useState('');
const [results, setResults] = useState(BOOKS);
const [pending, setPending] = useState(false);
useEffect(() => {
let ignore = false;
setPending(true);
const timer = setTimeout(async () => {
const found = await searchBooks(query);
if (!ignore) {
setResults(found);
setPending(false);
}
}, 250);
return () => { ignore = true; clearTimeout(timer); };
}, [query]);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search books" />{' '}
{pending && <span>⏳</span>}
<ul style={{ opacity: pending ? 0.5 : 1 }}>
{results.map((b) => <li key={b}>{b}</li>)}
{results.length === 0 && <li><em>No matches</em></li>}
</ul>
</div>
);
}Sending data
POST requests usually happen in event handlers, not effects — they're caused by a user action:
async function handleSubmit(e) {
e.preventDefault();
const res = await fetch('/api/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
if (!res.ok) return setError('Could not post');
setComments([...comments, await res.json()]);
}React 19's form Actions make this even simpler; see the React 19 Actions lesson.
Beyond useEffect
Effects work, but large apps quickly need caching, retries, background refresh and deduplication. Common choices:
| Tool | What it adds |
|---|---|
TanStack Query (useQuery) |
caching, refetching, pagination, mutations |
SWR (useSWR) |
lightweight stale-while-revalidate caching |
| Framework loaders (Next.js, React Router) | load data before the page renders, on the server |
use(promise) + Suspense |
read a promise during render (see Suspense & lazy) |
Tip: Whatever tool you use, always design all three states — loading, error, and empty results — not just the happy path.
Test yourself
Why can't the function passed to useEffect be async?
- Effects can't use promises
- An async function returns a Promise, but an effect must return nothing or a cleanup function
- async is not allowed in components
- It would run twice
Does fetch reject its promise on an HTTP 404 response?
- Yes, always
- No — check
response.okyourself - Only for POST requests
- Only in development
What does the ignore flag in an effect's cleanup protect against?
- Memory leaks in CSS
- A stale response overwriting newer data
- Double clicks
- Slow rendering