Sub topic 2
When to fetch: effects and dependencies
This chapter assumes you know React components, props, and JSX, the useState hook, and promises with async/await. It covers when a component should start a request. The next chapter writes the fetch itself.
Why fetching belongs in an effect
A component function runs on every render. React expects it to be pure: given the same props and state, it returns the same JSX and does nothing else. A network request is a side effect, because it reaches outside the component. If you call fetch in the function body, it fires on every render. When the response sets state, that causes another render, which fires another request. The result is an infinite loop.
useEffect solves this. It lets you run code after React has rendered and updated the screen. You pass it a function, and React calls that function after the render is committed.
import { useEffect } from 'react';
function Page({ pageId }) {
useEffect(() => {
console.log('Rendered with page', pageId);
}, [pageId]);
return <p>Page {pageId}</p>;
}The dependency array
The second argument to useEffect is the dependency array. It lists every reactive value the effect reads. Reactive values are props, state, and anything computed from them during render. React compares the array with the one from the previous render, using Object.is on each item.
| Dependency array | When the effect runs |
|---|---|
| Omitted | After every render |
| `[]` | After the first render only |
| `[userId]` | After the first render, and after any render where `userId` changed |
For fetching, the array answers the question "when should this request run again?" If the request depends on userId, then userId goes in the array. The effect then fetches again whenever the user changes.
Let the linter pick the dependencies
Do not choose the array by guessing. The rule is that every reactive value used inside the effect must appear in the array. The react-hooks/exhaustive-deps ESLint rule checks this for you.
A common mistake is leaving a value out so the effect "only runs once".
// Bug: the effect reads userId but does not list it
useEffect(() => {
fetch(`/api/users/${userId}`);
}, []);This fetches the first user and never updates. When userId changes, the screen shows the new ID but the old user's data. If you want the request to run only once, the request must not depend on any reactive value.
Another mistake is putting an object or function created during render into the array. A new object is created on each render, and Object.is sees it as changed every time. The effect then runs on every render. Prefer primitive values such as strings and numbers, or move the object inside the effect.
// Runs every render: options is a new object each time
const options = { userId };
useEffect(() => {
fetch(`/api/users/${options.userId}`);
}, [options]);
// Runs only when userId changes
useEffect(() => {
fetch(`/api/users/${userId}`);
}, [userId]);Effects are for synchronizing
Think of an effect as keeping something outside React in sync with your current props and state. Here, the outside thing is the server data for a given userId. Each time the inputs change, the effect brings the data back in sync. This view explains why the dependency array matters and prepares you for cleanup, which comes later.
Not every fetch needs an effect. If a request is the direct result of a click, such as submitting a form, run it in the event handler. Use an effect when the request should happen because the component is on screen with certain inputs.
Exercise
A component fetches /api/posts?page=${page} inside useEffect with an empty dependency array []. The user clicks "Next" and page changes from 1 to 2. What does the screen show, and how do you fix it?
Show answer
The effect does not run again, so the component keeps showing the data for page 1 while page is 2. Fix it by adding page to the dependency array: [page]. The effect then re-runs after every change of page.