Sub topic 2
What counts as a side effect
This chapter assumes you can write function components with JSX and use useState. It also assumes you know that a state change makes React call your component again, and that you are comfortable with closures, Promises and fetch. You don't need to know useEffect yet. The next chapters introduce it, and this one explains the problem it solves.
A working definition
A function has a side effect when it does something observable outside itself besides returning a value. Changing a global variable, writing to the screen, sending a network request and starting a timer are all side effects. The return value is the function's result. Everything else it changes in the world is a side effect.
In a React component, the result is the JSX you return. The component receives props and state, and it returns a description of the UI. Anything else the component does is a side effect. That includes work the component starts and work it leaves running after it returns.
Why this matters for rendering
React calls your component function to find out what the screen should look like. That call is the render, and React may make it more often than you expect:
- It may render again after any state or prop change in the component or its parents.
- In development under Strict Mode, it deliberately renders twice to expose impure code.
- With concurrent features, it may start a render and throw the result away before the screen is updated.
React can only do this safely if rendering is pure. A pure render gives the same output for the same props, state and context, and it changes nothing outside the component. Then an extra or discarded render costs a little time and has no other consequence.
Here is a component that breaks this rule:
import { useState } from 'react';
let renderCount = 0; // lives outside the component
function ClickReport() {
const [clicks, setClicks] = useState(0);
renderCount = renderCount + 1; // side effect: changes shared state during render
return (
<div>
<p>Clicks: {clicks}</p>
<p>Renders so far: {renderCount}</p>
<button onClick={() => setClicks(clicks + 1)}>Click</button>
</div>
);
}
export default ClickReport;The line renderCount = renderCount + 1 changes a variable that other code could also read. The number on screen now depends on how many times React chose to call the function, not on props and state. In Strict Mode the first render already shows 2. Nothing is wrong with React here. The component assumed that it is called exactly once per update, and React makes no such promise.
Side effects versus impure inputs
Two different problems make a render impure.
- Writing outside the component. Examples are changing a module variable, mutating a prop, or calling
fetch. This is a side effect in the strict sense. - Reading something that changes by itself.
Date.now(),Math.random()andwindow.innerWidthcan return different values on each call. The render then produces different output for identical props and state. This is not a side effect, but it breaks purity for the same reason.
A related example is document.title = .... That is a write to the outside world, so it is a side effect. Reading window.innerWidth during render is an impure input. Both belong outside the render body. The ways to handle each differ, and later chapters return to them.
Common side effects in components
| Action | Side effect? | Typical home |
|---|---|---|
| Return JSX computed from props and state | No | Render body |
| Filter or map an array into a new array | No | Render body |
| Build a local array and push into it during render | No (local mutation) | Render body |
| Set `document.title` | Yes | Effect |
| Add a `resize` or `keydown` listener | Yes | Effect |
| Start `setInterval` or `setTimeout` | Yes | Effect |
| Open a WebSocket or subscribe to a store | Yes | Effect |
| `fetch` data needed to show the component | Yes | Effect |
| `fetch` or POST because the user clicked Save | Yes | Event handler |
| Write to `localStorage` after the user changes a setting | Yes | Event handler |
| Mutate a prop or module-level variable | Yes | Nowhere. Don't do it. |
| `console.log` for debugging | Technically yes | Anywhere, but it is harmless |
Local mutation is fine
Purity does not forbid mutation. It forbids mutating things that existed before the render started, or that anything outside the render can see. A value you create inside the render and never share is yours to change:
function TagList({ tags }) {
const items = []; // created during this render
for (const tag of tags) {
items.push(<li key={tag}>{tag}</li>); // mutating our own array
}
return <ul>{items}</ul>;
}
export default TagList;Every render builds a fresh items array and no other code can see it. Calling tags.push(...) or tags.sort() on the prop would be a different matter. That changes data owned by the parent, and every later render would see the change.
Where side effects are allowed to live
If rendering must be pure, side effects need other places to run. React gives you two.
Event handlers. These are functions such as onClick and onChange that run because of a specific user action. React does not call them while rendering, so they may do anything:
import { useState } from 'react';
function SaveButton({ draft }) {
const [status, setStatus] = useState('idle');
async function handleClick() {
setStatus('saving');
const res = await fetch('/api/drafts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(draft),
});
setStatus(res.ok ? 'saved' : 'error');
}
return (
<button onClick={handleClick} disabled={status === 'saving'}>
Save ({status})
</button>
);
}
export default SaveButton;The request is sent because the user clicked. Rendering the button again does not send it again.
Effects. Some side effects have no triggering click. Keeping the tab title in sync with the current page, subscribing to a chat room while a component is on screen, and loading the profile for the user ID in props are examples. The component's presence on screen, or a value it shows, causes the work. For these, React offers useEffect, which runs a function after the render has been committed to the screen:
import { useEffect } from 'react';
function PageTitle({ title }) {
useEffect(() => {
document.title = title;
}, [title]);
return <h1>{title}</h1>;
}
export default PageTitle;Don't worry about the second argument for now. The following chapters cover the syntax, timing and dependency array in detail. What matters here is the placement: the write to document.title is not in the render body. It is in a function that React calls later, at a point where it is safe.
The word "effect" in useEffect comes from "side effect". The hook exists to hold side effects that rendering itself caused.
Edge cases and gotchas
- Calling a state setter during render is also a side effect, because it schedules another render. React allows one narrow pattern, updating the component's own state while rendering, but you will rarely need it. Setting a parent's or another component's state during render is an error.
- Writing to a ref during render (
ref.current = value) changes something that outlives the render. Put such writes in handlers or effects. The exception is lazy initialization, where you set the ref only if it is still empty. - Starting a request in the render body sends a new request on every render. Because setting state from the response triggers another render, this can turn into an endless loop of requests.
- Logging is a side effect, but it changes nothing your UI depends on. It is the one impure thing that is routinely fine in a render body.
Key points
- A side effect is anything a function does beyond returning its result. In a component, the result is the JSX.
- Rendering must be pure because React may call it many times, twice in development, and sometimes discard the result.
- Mutating values you created during this render is fine. Mutating props, state objects or outside variables is not.
- Side effects belong in event handlers when a user action causes them, and in effects when the component's presence or values cause them.
Exercise
A component renders a list and contains the line items.sort(), where items is a prop. Another line, const sorted = [...items].sort(), appears in a second component. Which one has a side effect during render, and why?
Show answer
The first. items.sort() sorts the array in place, so it mutates the prop that the parent owns, and the parent's data changes on every render. The second copies the array into a new local one first, so it only mutates a value created during that render, which is allowed.
Exercise
For each task, say whether it belongs in the render body, an event handler or an effect: (a) computing the total price from a cart prop, (b) sending an order when the user clicks "Buy", (c) opening a WebSocket connection to a chat room for as long as the chat panel is on screen.
Show answer
(a) Render body, because it is a pure calculation from props. (b) Event handler, because a specific user action causes it. (c) Effect, because the panel being on screen causes it, not a single click.