Sub topic 3
Fetching data inside useEffect
This chapter assumes you know promises and async/await, React components, props, JSX, and the useState hook. It also assumes you know basic HTTP: methods, status codes, and JSON. You should have seen the Fetch API and the dependency array of useEffect in the previous chapters.
Why fetching belongs in an effect
A component function must be pure. Rendering it should not send network requests, because React can call it many times. A request is a side effect: work that reaches outside the component. useEffect is the place for it. React runs the effect after it commits the render to the screen.
The pattern has three parts:
- State holds the result of the request.
- An effect starts the request after render.
- The
.thenhandlers write the result into state, which triggers a new render.
A first version
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
setIsLoading(true);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => {
setUser(data);
setIsLoading(false);
})
.catch((err) => {
if (err.name === 'AbortError') return;
setError(err);
setIsLoading(false);
});
return () => controller.abort();
}, [userId]);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{user.name}</h1>;
}This example already includes the cleanup function and the AbortController. A later chapter explains why they matter. For now, focus on the flow.
How it runs
The first render always shows "Loading...", because the data cannot exist yet. The effect runs after that render. When the response arrives, the state updates cause the second render.
Details that matter
- The dependency array is
[userId]. The effect readsuserId, so it must be listed. WhenuserIdchanges, React runs the cleanup for the old effect and then runs the effect again. fetchdoes not reject on HTTP errors. A 404 or 500 still resolves. Checkresponse.okand throw, as the example does. Only network failures reject on their own.- Reset state at the start of the effect. Without
setError(null), an old error stays visible while the new request runs. - The effect function cannot be
async. An async function returns a promise, but React expects either nothing or a cleanup function. Use.thenchains, or define an async function inside the effect and call it.
Common mistakes
| Mistake | Result |
|---|---|
| Omitting `response.ok` | Error pages are parsed as data, or `response.json()` fails with a confusing message |
| Omitting a dependency | The component keeps showing data for the old `userId` |
| Calling `setState` in render | Infinite render loop |
| Not handling `AbortError` | A cancelled request is shown as a failure |
Exercise
A user navigates from /users/1 to /users/2, so userId changes from 1 to 2. In the component above, what happens to the request for user 1, and why does the effect run again?
Show answer
The effect lists userId in its dependency array, so React sees a change. It first runs the cleanup function, which aborts the request for user 1. The catch handler ignores the resulting AbortError. Then React runs the effect again and starts a request for user 2.
Exercise
The server returns status 500 with an HTML error page. Without the response.ok check, which step would fail, and what would the user see?
Show answer
fetch resolves normally for a 500, so response.json() would try to parse HTML and reject with a SyntaxError. The catch handler would store that error, and the user would see a confusing parse message instead of a clear status message.