Explain it simply
Explain it simply
Imagine a component that wants to show one blog post stored on a server. The data does not arrive instantly: the network takes time and sometimes fails. So the screen must handle three situations: still waiting, something went wrong, and here is the data.
It is like ordering at a restaurant. After you order, the waiter says the food is being cooked; if the kitchen ran out, the waiter says so; finally the plate arrives. In React you place the order inside useEffect, and you remember the waiter's three possible answers with useState.
Problem → Why → Solution
The problem: a stale response that arrives late
The Post component below fetches again every time its postId prop changes. It looks fine. But suppose the user clicks post 1 and then immediately clicks post 2. If the request for post 1 is slow and the request for post 2 is fast, post 2's data arrives first, then post 1's data lands and overwrites it.
The result: the URL and the selected tab say post 2, but the title on screen belongs to post 1. And if the server answers with a 404, this code treats the error body as if it were a post and keeps going.
function Post({ postId }) {
const [post, setPost] = useState(null);
useEffect(() => {
fetch(`/api/posts/${postId}`)
.then((res) => res.json()) // no res.ok check
.then((data) => setPost(data)); // whichever response lands LAST wins
}, [postId]); // no cleanup function
return <h1>{post?.title}</h1>;
}Why does this happen?
Network requests do not come back in the order they were sent. Each effect starts its own request and has no idea that its postId has become stale. Without a cleanup function, React has no way to tell the old effect to stand down. On top of that, fetch() only rejects when the network itself fails; 404 and 500 responses resolve normally.
Core concept: fetching as a synchronizing Effect
Do not think of a fetch inside useEffect as "code that runs once after rendering". Think of it as "keep this component synchronized with the server for this postId". Whenever postId changes, React runs the old effect's cleanup first and only then runs the new effect. You use that ordering to switch off the old request. There are four parts.
1. Model all three states
Hold loading, error and data as state and return a UI for each one. Reading post.title before the data arrives crashes with a property read on null.
2. Check response.ok yourself
fetch() resolves for any response the server sends. Throwing when the status is outside 200-299, so the catch branch handles it, is your job.
3. Switch off the old request in cleanup
Declare let ignore = false inside the effect and set it to true in cleanup. Checking ignore before calling setState means a stale response can no longer touch state. Calling AbortController.abort() as well makes the browser stop the download, which saves bandwidth.
4. Understand Strict Mode's double run
In development, Strict Mode mounts, unmounts and remounts the component, so the effect runs twice. A first request marked canceled in the Network tab is proof that your cleanup works, not a bug. Production does not do this extra run.
function Post({ postId }) {
const [result, setResult] = useState({ id: null, post: null, error: '' });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
fetch(`/api/posts/${postId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((post) => { if (!ignore) setResult({ id: postId, post, error: '' }); })
.catch((err) => {
if (!ignore) setResult({ id: postId, post: null, error: err.message });
});
return () => { ignore = true; controller.abort(); };
}, [postId]);
if (result.id !== postId) return <p>Loading…</p>;
if (result.error) return <p role="alert">{result.error}</p>;
return <h1>{result.post.title}</h1>;
}This version does not store loading as separate state. When result.id differs from the current postId, it derives "this post's data has not arrived yet". That is why Loading… appears in the very render where postId changes, without the old title flashing for a moment. The aborted request rejects with an AbortError, but by then ignore is true, so it never shows up as an error message.
Race without cleanup
--------------------
time --->
click post 1 request A ---------------------------> lands, sets post 1
click post 2 request B -------> lands, sets post 2
screen: Loading post 2 shown post 1 shown (WRONG)
with cleanup: clicking post 2 runs A's cleanup -> ignore = true + abort()- postId changes
- Cleanup switches off the old request
- The new effect starts a new request
- State is set only if not ignored
Every request belongs to the postId that started it. Once the dependency changes, that request's answer has lost the right to change the screen.
General pattern
useEffect(() => {
let ignore = false;
const controller = new AbortController();
loadSomething(dependency, { signal: controller.signal })
.then((data) => { if (!ignore) setData(data); })
.catch((error) => { if (!ignore) setError(error); });
return () => { ignore = true; controller.abort(); };
}, [dependency]);One effect starts one request for one dependency value, and its cleanup switches that request off. Always check ignore before setting state.
Fetch one post and render three states
The component below fetches one post from a single fixed URL when it mounts. Because the URL never changes, no race can happen, so leaving out cleanup is acceptable in this version. Study the three states, the response.ok check and the finally block that turns loading off. The cleanup pattern above becomes necessary the moment the id comes from a prop.
import { useEffect, useState } from 'react';
function Post() {
const [post, setPost] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function loadPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Failed to load post');
const data = await response.json();
setPost(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
loadPost();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>{error}</p>;
return <h1>{post.title}</h1>;
}Code breakdown
- Loading starts as true
const [loading, setLoading] = useState(true);On the first render there is no data yet, so loading starts as true. Starting with false would make the first render read post.title on null and crash.
- Turn HTTP errors into exceptions
if (!response.ok) throw new Error('Failed to load post');A 404 or 500 still resolves the fetch. This line turns those responses into an exception so they reach the catch block.
- Store the error message
setError(err.message);Both network failures and HTTP errors end up here. Keeping the message in state lets the render show it to the user.
- Loading ends either way
setLoading(false);Because it sits in finally, loading turns off whether the request succeeded or failed, without repeating the call in both try and catch.
- Run once after mount
}, []);The empty array says this effect depends on no props or state. As soon as a prop appears in the URL, it must go into the array, together with a cleanup function.
- Early returns per state
if (loading) return <p>Loading...</p>;Checking loading and error first and returning early guarantees that post exists by the time the last line runs.
Loading shows first, and once the data arrives, the post title appears. If the API has an issue, an error message shows instead.Why data libraries and framework loaders exist
Fetching inside an Effect by hand is great for learning, but as an app grows the same chores keep coming back. Leaving a page and returning downloads the data again. Two components asking for the same URL at the same time send two requests. A parent fetches, then renders a child that fetches next, so requests line up one after another in a waterfall.
The React documentation itself recommends using your framework's data fetching or a client-side cache library in production apps.
| Approach | What you get | What it costs |
|---|---|---|
| useEffect + fetch | No dependency, every step visible | You hand-write cache, retry, dedupe |
| TanStack Query, SWR | Caching, deduping, retries, refetching | A library and its cache-key rules |
| Framework loader (React Router, Next.js) | Route data starts before render, in parallel | You follow the framework's routing model |
use() and Suspense: reading a promise during render
React 19 adds the use() API. When you read a promise during render with use(promise), the component suspends until it resolves and the nearest Suspense boundary shows its fallback. If the promise rejects, the nearest error boundary catches it.
The important rule: do not create the promise inside the component on every render. If each render makes a fresh promise, React never sees a settled answer. use() is meant for promises created by a framework loader, a Server Component or a caching library, and passed down as a prop.
import { Suspense, use } from 'react';
function Comments({ commentsPromise }) {
const comments = use(commentsPromise); // suspends until it resolves
return comments.map((c) => <p key={c.id}>{c.text}</p>);
}
// commentsPromise comes from a loader or a cache, not from Comments itself
<Suspense fallback={<p>Loading comments…</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>In real projects
In real projects
Search boxes are where race conditions show up most. The user types "rea" and then "react", two requests go out, and the results for "rea" often arrive last. An effect with cleanup ignores them. On dashboards, many widgets ask for the same data, so a cache library that merges those calls into one request pays off quickly.
Most teams do not write fetch directly in components. They put a function such as getPost(id, { signal }) in a file like api.js. The base URL, auth headers and the response.ok check live in one place, so components only care about the three states. Loading UI is usually a skeleton placeholder instead of the word "Loading...", so the layout does not jump when data arrives.
Common mistakes
Common mistakes
Making the effect function itself async
Writing useEffect(async () => { ... }) makes the effect return a promise. React expects a cleanup function, warns, and you lose cleanup entirely. Declare an async function inside the effect and call it, as the example does.
Adding the dependency but forgetting cleanup
Putting [postId] in the array without an ignore flag brings back the race from the problem section. Whenever a request depends on a prop or state value, write the cleanup too.
Showing AbortError to the user
A request aborted by cleanup lands in catch. Calling setError without checking ignore shows the user a message like "The user aborted a request" just for switching tabs. Do not report your own cancellation as an error.
Mini challenge
A UserCard that can switch users
Write a UserCard that fetches /api/users/:id whenever a user ID (1, 2 or 3) is chosen in a select box, and shows the name and email. Even when the user switches quickly, only the last chosen user may appear.
- Use userId as the dependency and write a cleanup with an ignore flag and AbortController
- Throw with a message like "HTTP 404" when response.ok is false
- Derive loading from result.id not matching userId
- Show errors in a paragraph with role="alert"
import { useEffect, useState } from 'react';
function UserCard({ userId }) {
// TODO: one state object { id, user, error }
useEffect(() => {
// TODO: ignore flag + AbortController
// TODO: fetch /api/users/:id, check res.ok, store user or error
// TODO: return a cleanup that ignores and aborts
}, [/* TODO */]);
// TODO: loading -> error -> name + email
}
export default function UserPicker() {
// TODO: userId state starting at 1, a <select> with 1-3, then <UserCard />
}Expected: First "Loading user…" appears, then user 1's name and email. Switching quickly from 2 to 3 shows only user 3, and the Network tab marks user 2's request as canceled. An unknown ID shows an "HTTP 404" alert.
Show hint
Store id: userId together with each result. In render, if result.id !== userId, just show Loading. A select's value is a string, so convert it with Number().
Show solution
import { useEffect, useState } from 'react';
function UserCard({ userId }) {
const [result, setResult] = useState({ id: null, user: null, error: '' });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
async function load() {
try {
const res = await fetch(`/api/users/${userId}`, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
if (!ignore) setResult({ id: userId, user, error: '' });
} catch (err) {
if (!ignore) setResult({ id: userId, user: null, error: err.message });
}
}
load();
return () => {
ignore = true;
controller.abort();
};
}, [userId]);
if (result.id !== userId) return <p>Loading user…</p>;
if (result.error) return <p role="alert">{result.error}</p>;
return (
<article>
<h2>{result.user.name}</h2>
<p>{result.user.email}</p>
</article>
);
}
export default function UserPicker() {
const [userId, setUserId] = useState(1);
return (
<section>
<label>
User{' '}
<select value={userId} onChange={(e) => setUserId(Number(e.target.value))}>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
</select>
</label>
<UserCard userId={userId} />
</section>
);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Every fetching component needs three UIs: loading, error and data
- fetch() does not reject on 404/500, so check response.ok yourself
- When a request depends on props or state, write a cleanup with an ignore flag and abort()
- Reach for a data library or framework loader to get caching, deduping and no waterfalls
- use(promise) should read a promise that is not recreated on every render
React Documentation — React