React / 30
Fetching data with useEffect
Render first, fetch in an effect, then fill in the data. Plus the three things tutorials skip, which are HTTP errors, cancelling, and stale responses.
Render first, fetch after
There are two ways to get data on screen:
- Load, then render: wait for the data, then show the page.
- Render, then fetch: show the page's frame straight away, fetch, then re-render with the data.
Load, then render
wait for data before showing anything
what the user sees at 0.5s
- 0.0sRequest the data
- …Nothing on screen. Is it broken?
- 1.2sData arrives, first render shows the page
Render, then fetch
what React apps do with useEffect
what the user sees at 0.5s
- 0.0sFirst render: header + placeholder cards
- 0.0sEffect runs after paint and starts the fetch
- 1.2sData arrives → set state → re-render with real cards
React apps use the second way, and useEffect is exactly the "after the first render" slot it needs.
The basic pattern
import { useEffect, useState } from "react";
export default function RecipeList() {
const [recipes, setRecipes] = useState([]);
useEffect(() => {
async function loadRecipes() {
const res = await fetch("https://dummyjson.com/recipes?limit=12");
const data = await res.json();
setRecipes(data.recipes);
}
loadRecipes();
}, []);
return (
<ul>
{recipes.map((recipe) => (
<li key={recipe.id}>{recipe.name}</li>
))}
</ul>
);
}First render
recipesis[], so an empty list paints instantly.Effect runs
After paint,loadRecipes()starts the request.[]means it only happens on mount.Data arrives
res.json()turns the response body into a JS object.Set state, re-render
setRecipes(...)triggers a re-render, and the list fills in.
Don't
Make the effect itself async
useEffect(async () => {
const res = await fetch(url);
setRecipes((await res.json()).recipes);
}, []);An async function always returns a Promise. React expects nothing or a cleanup function, so it warns, and it can't use a Promise as cleanup.
Do
Async function inside, then call it
useEffect(() => {
async function load() {
const res = await fetch(url);
setRecipes((await res.json()).recipes);
}
load();
}, []);The effect returns nothing (or a real cleanup), and you still get await.
Make it real: errors and cancelling
The basic version ignores three things that happen every day: the server answers with an error, the request fails, or the component is gone before the answer arrives.
import { useEffect, useState } from "react";
export default function RecipeList() {
const [recipes, setRecipes] = useState([]);
const [status, setStatus] = useState("loading"); // "loading" | "error" | "success"
useEffect(() => {
const controller = new AbortController();
async function loadRecipes() {
try {
const res = await fetch("https://dummyjson.com/recipes?limit=12", { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setRecipes(data.recipes);
setStatus("success");
} catch (err) {
if (err.name !== "AbortError") setStatus("error");
}
}
loadRecipes();
return () => controller.abort();
}, []);
if (status === "loading") return <p>Loading…</p>;
if (status === "error") return <p>Couldn't load recipes.</p>;
return <ul>{recipes.map((r) => <li key={r.id}>{r.name}</li>)}</ul>;
}res.ok:fetchdoes not throw on a 404 or 500. It only rejects when the request fails completely (offline, CORS, aborted). Checkres.okyourself.try / catch: one place to catch network failures, bad JSON and your ownthrow.AbortController: the cleanup cancels the request if the component unmounts. The cancelledfetchrejects with anAbortError, which you ignore. This also tidies up StrictMode's extra dev run: the first request is aborted, and the second one wins.
Stale responses (race conditions)
When an effect depends on something, like the recipe id the user picked, several requests can be in flight at once. Responses don't arrive in the order you sent them. Try it:
Two requests, wrong winner
Try itcleanup sets ignore = true
you picked
nothing yet
screen shows
nothing yet
- No requests yet.
The fix is the cleanup. When id changes, React runs the previous effect's cleanup, which marks that request as stale:
useEffect(() => {
let ignore = false;
fetch(`https://dummyjson.com/recipes/${id}`)
.then((res) => res.json())
.then((data) => {
if (!ignore) setRecipe(data);
});
return () => {
ignore = true; // this request is old now, drop its answer
};
}, [id]);An ignore flag works with any promise. AbortController does the same job and stops the download. Either is fine.
What real apps use
Writing loading, error, cancelling and caching code in every component gets old fast. React's own docs recommend these for real projects:
-
A data library like TanStack Query (or SWR). It handles caching, retries, refetching and race conditions for you:
import { useQuery } from "@tanstack/react-query"; function RecipeList() { const { data, isPending, error } = useQuery({ queryKey: ["recipes"], queryFn: () => fetch("https://dummyjson.com/recipes").then((r) => r.json()), }); if (isPending) return <p>Loading…</p>; if (error) return <p>Couldn't load recipes.</p>; return <ul>{data.recipes.map((r) => <li key={r.id}>{r.name}</li>)}</ul>; }(It needs a
<QueryClientProvider>at the root of your app.) -
A framework or router loader. React Router loaders and Next.js Server Components fetch data before or while the page renders, so there's no render-then-fetch delay.
-
React 19's
use(promise)with<Suspense>. A component callsuse(promise)and suspends until it resolves. The nearest<Suspense fallback={…}>shows the loading UI, and a rejected promise goes to the nearest error boundary. The catch: the promise must be created once, outside render (by a loader, a Server Component or a cache). Writinguse(fetch(url))in a component makes a new promise every render, so it shows the fallback forever.
Learning the useEffect version first is still worth it. It's what those tools do for you under the hood.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
