Sub topic 3
Fetching data inside useEffect
This chapter assumes you know promises and async/await, React props and JSX, and useState. It also assumes you have seen the Fetch API and the basics of useEffect and its dependency array. The goal here is to combine them into a working pattern for loading data when a component appears or when its inputs change.
Why fetching belongs in an effect
A component function must be pure. React may call it many times, and every call should compute JSX from props and state without side effects. A network request is a side effect, because it reaches outside the component. If you call fetch directly in the function body, it runs on every render. When the response arrives and you store it in state, that triggers another render, which sends another request. The result is an endless loop of requests.
useEffect solves this. React runs the effect after it has rendered and committed the result to the screen. The dependency array tells React when to run it again.
The flow looks like this:
The component always renders at least twice. The first render has no data. The second render happens after the response arrives. Your JSX must handle both.
The basic pattern
Here is the smallest useful version. It uses promise chaining so each step is visible.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => setUser(data))
.catch((error) => console.error(error));
}, [userId]);
if (user === null) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}Four details matter:
- State starts as
null. The first render has nothing to show, so the component returns a placeholder. - The effect checks
response.ok.fetchonly rejects its promise on network failures. A 404 or 500 response still resolves, so you must turn it into an error yourself. setUseris called inside.then. Setting state schedules the second render.[userId]is the dependency array. The effect runs after the first render and again after any render whereuserIdchanged. If a parent changesuserIdfrom 1 to 2, the component fetches user 2.
Using async/await in an effect
Most people prefer async/await. You cannot make the effect callback itself async, because an async function returns a promise. React expects the callback to return either nothing or a cleanup function. A promise is neither, and React warns about it.
Define an async function inside the effect and call it:
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
async function loadUser() {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
setUser(data);
}
loadUser().catch((error) => console.error(error));
}, [userId]);
if (user === null) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}Define loadUser inside the effect, not outside the component. A function defined inside can read userId directly, and the linter sees that userId is the only reactive value the effect uses. If you define it outside, you have to list the function in the dependency array and stabilize it. Doing so adds work without benefit.
The trailing .catch is required. Without it, a thrown error becomes an unhandled promise rejection. You will replace the console.error with real error state in the next chapter.
Choosing the dependency array
The dependency array decides how often the request runs. The linter rule react-hooks/exhaustive-deps checks it, and you should leave it enabled.
| Dependency array | When the effect runs | Typical use |
|---|---|---|
| `[]` | After the first render only | Data that does not depend on props or state |
| `[userId]` | After the first render, then whenever `userId` changes | Data keyed by an input |
| Omitted | After every render | Almost never correct for fetching |
Every prop or state value the effect reads must appear in the array. If it does not, the effect uses a stale value and keeps showing data for an old input.
Mistake: no dependency array
useEffect(() => {
fetch('/api/users')
.then((response) => response.json())
.then((data) => setUsers(data));
}); // no arrayThis runs after every render. Each response calls setUsers, which renders again, which runs the effect again. The browser's network tab fills with requests, and the server may start rate limiting you. Always pass an array.
Mistake: an object or array that is recreated each render
function Results({ query }) {
const options = { query, limit: 10 }; // new object every render
useEffect(() => {
// fetch using options...
}, [options]); // runs after every render
}React compares dependencies with Object.is. A new object literal is never equal to the previous one, so the effect runs after every render. Depend on the primitive values instead, such as [query]. You can also build the object inside the effect.
Effects versus event handlers
Not all fetching belongs in an effect. Ask what causes the request:
- The component is displayed, or its inputs changed. Use an effect. Loading a profile page is an example.
- The user did something. Use an event handler. Submitting a form or clicking "Load more" are examples. The handler calls
fetchdirectly, and no effect is needed.
Putting a user-triggered request in an effect often forces you to store a "please fetch now" flag in state. That is a sign you should call fetch in the handler instead.
What this version still gets wrong
The pattern above works for a demo, but it has gaps. You will close them in the next chapters:
- It conflates "loading" with "no data." If the request fails, the user sees "Loading..." forever.
- When
userIdchanges, the old user stays on screen until the new response arrives. - If
userIdchanges from 1 to 2 and the response for 1 arrives after the response for 2, the screen shows the wrong user. Responses can arrive out of order. - Nothing cancels a request when the component unmounts. Its response then arrives with nobody to use it.
Summary of the pattern
- Keep the fetched data in state, starting at an empty value.
- Start the request in
useEffect, after render. - Use an inner
asyncfunction or a promise chain. Never make the effect callbackasync. - Check
response.okand throw on failure. - Handle rejections with
.catch. - List every value the effect reads in the dependency array.
Exercise
A teammate writes useEffect(async () => { const r = await fetch(url); setData(await r.json()); }, [url]);. Name the problem with the callback, and write the fix in one sentence.
Show answer
An async function returns a promise, but React expects the effect callback to return nothing or a cleanup function, so it warns and cleanup cannot work. Fix it by defining an async function inside the effect and calling it, for example useEffect(() => { async function load() { ... } load().catch(console.error); }, [url]);.
Exercise
A component calls useEffect(() => { fetch('/api/items').then((r) => r.json()).then(setItems); }); with no dependency array. Describe what happens, and name the smallest change that fixes it if the data does not depend on any props or state.
Show answer
The effect runs after every render. Each response calls setItems, which causes a render, which starts another request, so requests repeat endlessly. Adding an empty dependency array [] makes the request run only once, after the first render.