Sub topic 2
What counts as a side effect
This chapter assumes you can write function components with JSX and useState, and that you know a state change makes React call your component again. The previous chapter covered pure rendering. Here you learn to spot the code that breaks purity.
The definition
A side effect is anything your component does that reaches outside the calculation of its own JSX. Rendering should only read props and state and return a description of the UI. Any work beyond that is a side effect.
| Code | Side effect? | Why |
|---|---|---|
| `items.filter(i => i.done)` on a prop | No | It only computes a value. |
| `document.title = "Inbox"` | Yes | It changes the browser, not the output. |
| `fetch("/api/user")` | Yes | It talks to the network. |
| `setInterval(tick, 1000)` | Yes | It schedules work that outlives the render. |
| `localStorage.setItem("k", v)` | Yes | It writes to storage. |
| `console.log(props)` | Technically yes | It is harmless, but it is still output to the outside world. |
| `counter++` on a variable declared outside the component | Yes | It mutates shared data. |
Why it matters during render
React may call your component more than once for a single screen update. It may also pause a render and discard it. If a render has side effects, they can run twice, run at the wrong time, or run for output the user never sees.
let renderCount = 0;
// Impure: writes to a module variable and to the document during render.
function BadGreeting({ name }) {
renderCount++;
document.title = `Hello ${name}`;
return <h1>Hello {name}</h1>;
}
// Pure: the same props always give the same JSX and nothing else happens.
function Greeting({ name }) {
return <h1>Hello {name}</h1>;
}BadGreeting returns the right JSX, so it looks fine. The bug is that renderCount depends on how often React chose to call the function, not on what the user sees.
Where side effects belong
A side effect has two valid places to live:
- Event handlers. Use these when a user action causes the work, such as clicking Save and sending a request.
- Effects. Use
useEffectwhen the component being on screen causes the work, such as subscribing to a chat room while it is displayed.
import { useState } from 'react';
function SaveButton({ draft }) {
const [status, setStatus] = useState('idle');
// Side effect inside an event handler: it runs only when the user clicks.
async function handleClick() {
setStatus('saving');
await fetch('/api/draft', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ draft }),
});
setStatus('saved');
}
return <button onClick={handleClick}>Save ({status})</button>;
}The diagram shows the order. Rendering sits between a state change and the DOM update, so it is the one step that must stay free of side effects.
Common errors
- Fetching in the component body. A
setStatecall after the response triggers a re-render, which fetches again, and this loops forever. - Mutating props or state objects. Writing
props.items.push(x)changes data that belongs to the parent. Copy first and set new state. - Using an effect for a click. If a button press causes the work, put it in the handler, not in an effect that watches state.
Exercise
A component calls localStorage.setItem("theme", theme) directly in its body. Is that a problem, and where should the call go if the theme should be saved whenever it changes?
Show answer
Yes. Writing to storage is a side effect, and it runs on every render, including renders React may repeat or discard. If the user picks a theme with a control, put the call in that control's event handler. If the stored value must stay in sync with a theme state however it changes, move the call into useEffect(() => { localStorage.setItem("theme", theme); }, [theme]).