Sub topic 2
When to Fetch: Effects and Dependencies
This chapter assumes you know promises and async/await, React components, props, JSX, and useState. It also assumes you know basic HTTP: methods, status codes, and JSON. It covers when React code should run a fetch and how the dependency array controls that timing. Loading states, error handling, and cancellation come in later chapters, so the examples here leave them out on purpose.
Why fetching belongs in an effect
React calls your component function to work out what the screen should look like. That call is expected to be pure. The same props and state should produce the same JSX, and nothing outside the component should change. React may call the function more than once, or discard a result, so a fetch placed directly in the body could fire on every render.
A network request is a side effect, meaning work that reaches outside the render calculation. React gives you two places to run side effects:
- Event handlers run because the user did something, such as a click or a form submit. Fetch here when an action causes the request.
- Effects run because the component is on screen, or because a value it depends on has changed. Fetch here when the request is needed to display the component.
| Situation | Where to fetch |
|---|---|
| User clicks "Save" and the app sends a POST | Event handler |
| User clicks "Load more" | Event handler |
| A profile page needs the user's data when it opens | Effect |
| A chart must reload when the selected date range changes | Effect |
If you can name the user action that triggers the request, use an event handler. An effect is for synchronizing the component with data it needs just by being displayed.
How an effect runs
useEffect takes a function and an optional array of dependencies.
import { useEffect, useState } from 'react';
function UserName({ userId }) {
const [name, setName] = useState(null);
useEffect(() => {
async function load() {
const response = await fetch(`/api/users/${userId}`);
const user = await response.json();
setName(user.name);
}
load();
}, [userId]);
return <p>{name ?? 'Loading...'}</p>;
}The order of events is:
- React renders the component and calls your function with the current props and state.
- React updates the DOM, and the browser can paint.
- After that, React runs the effect function.
- The fetch finishes later, and
setNametriggers a new render.
The effect never runs during the render itself. The first paint shows "Loading..." because name starts as null.
Why the effect callback is not async
You may be tempted to write useEffect(async () => { ... }). An async function always returns a promise. React expects the callback to return either nothing or a cleanup function, so a promise breaks that contract and React will warn you. Declare an async function inside the effect and call it, as load does above. A .then() chain also works.
The dependency array
The second argument tells React when to run the effect again. After each render, React compares the new array with the one from the previous render, item by item, using Object.is. If every item is equal, the effect is skipped.
| Form | When the effect runs | Typical use |
|---|---|---|
| `useEffect(fn)` | After every render | Rarely right for fetching |
| `useEffect(fn, [])` | Once after the first render | Data that depends on nothing in the component |
| `useEffect(fn, [a, b])` | After the first render and whenever `a` or `b` changes | Data that depends on props or state |
Object.is compares primitives by value, so 42 equals 42 and 'abc' equals 'abc'. It compares objects, arrays, and functions by identity, meaning whether they are the same object in memory. Two arrays with the same contents are different values if they were created separately.
Declare what the effect reads
The rule is that the array must list every reactive value the effect uses. A reactive value is a prop, a piece of state, or any variable or function declared inside the component body. Values defined outside the component, such as module constants, are not reactive and do not belong in the array.
You do not choose dependencies. They are a fact about your code, and the react-hooks/exhaustive-deps ESLint rule checks them. Treat its warnings as bugs to fix.
Suppose the effect above used an empty array:
useEffect(() => {
async function load() {
const response = await fetch(`/api/users/${userId}`);
const user = await response.json();
setName(user.name);
}
load();
}, []); // wrong: the effect reads userIdThe effect captures userId from the first render. If the parent later passes a different userId, the effect does not run again, and the component keeps showing the first user. This is a stale closure: the function remembers old values because React was told nothing had changed.
With [userId], a new id leads to a new effect run, and that run calls fetch with the new URL. That is the main reason to fetch in an effect: the request follows the inputs.
Dependencies that change on every render
The most common effect bugs come from dependencies that look stable but are new values on every render.
Objects and arrays created in the body
function Search({ query }) {
const [results, setResults] = useState([]);
const params = { q: query, limit: 10 }; // new object every render
useEffect(() => {
fetch(`/api/search?q=${params.q}&limit=${params.limit}`)
.then((response) => response.json())
.then(setResults);
}, [params]); // changes every render
return <p>{results.length} results</p>;
}Each render creates a new params object, so Object.is reports a change and the effect runs. The effect calls setResults with a new array, which triggers a render, which creates a new params, and the loop continues. The browser's network tab fills with identical requests.
The simplest fix is to depend on the primitive values and build the object inside the effect.
function Search({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const params = new URLSearchParams({ q: query, limit: '10' });
fetch(`/api/search?${params}`)
.then((response) => response.json())
.then(setResults);
}, [query]);
return <p>{results.length} results</p>;
}Now the only dependency is the string query, and the effect runs only when the user types something new. If the object must exist outside the effect, either move it to module scope when it never changes, or wrap it in useMemo. Functions declared in the body have the same problem and can be fixed with useCallback, but moving them into the effect is usually simpler.
No dependency array at all
useEffect(() => {
fetch('/api/items')
.then((response) => response.json())
.then(setItems);
}); // no arrayThis runs after every render. setItems receives a new array each time, which causes a render, which runs the effect. The same loop appears, with no object involved. If you meant "once," pass [].
Common mistakes
- Fetching in the render body. The request fires on every render. Move it into an effect or an event handler.
- Using an effect for an action. Sending a POST because a flag in state changed is fragile. Put the request in the click handler instead.
- Passing an
asyncfunction touseEffect. Declare an inner function and call it. - Using
[]while reading props or state. The effect uses stale values. List everything it reads. - Putting unstable objects or functions in the array. This causes repeated fetching. Depend on primitives, or memoize.
- Setting state that feeds the dependencies. If the effect updates a value it also depends on, it can retrigger itself.
Exercise
A component receives a categoryId prop and has this effect: useEffect(() => { fetch('/api/products?category=' + categoryId).then((r) => r.json()).then(setProducts); }, []);. A user switches categories, but the product list never changes. Why does this happen, and what is the fix?
Show answer
The dependency array is empty, so the effect runs only after the first render and captures the first categoryId. Later changes to the prop do not re-run it, so the list stays stale. The effect reads categoryId, which is a reactive value, so it must be listed: }, [categoryId]);. React then re-runs the effect whenever the category changes.
Exercise
A component builds const filters = { status: 'open' }; in its body and uses [filters] as the dependency array of a fetching effect that calls setTickets with the response. The network tab shows endless requests. Explain the cause and give two ways to fix it.
Show answer
filters is a new object on every render, so Object.is sees a changed dependency each time. The effect runs, setTickets triggers a render, and the loop repeats. Fix 1: depend on the primitive ('open', or a status variable) and build the request inside the effect. Fix 2: move the constant object outside the component, or wrap it in useMemo so its identity stays the same between renders.