Sub topic 2
Rendering is a calculation, not a place for side effects
This chapter assumes you can write function components with JSX, use useState and props, and have seen useEffect with a dependency array. It also assumes you know React re-renders a component when its state or props change.
The rest of this tutorial replaces unnecessary Effects with simpler patterns. Most of those replacements depend on one rule: rendering must be a pure calculation. This chapter explains that rule, shows how to spot violations, and says where side effects belong instead.
What "render" means
React uses "render" for the moment it calls your component function. The function receives props and state, and it returns JSX that describes the screen. React compares that JSX with the previous result and updates the DOM only where something changed.
Calling your function is not the same as updating the screen. React may call a component and then throw the result away. It may call it twice in a row in development. It may pause a render and resume it later, or start a render and abandon it because newer input arrived. Your component cannot control how many times, or whether, a given render call "counts".
This only works if calling the function has no consequences beyond returning JSX. That property is called purity.
What a pure component does
A pure component follows two rules:
- It minds its own business. It does not change any object or variable that existed before it was called.
- Same inputs, same output. Given the same props, state, and context, it returns the same JSX.
Think of a spreadsheet formula such as =A1 + B1. The formula reads cells and produces a value. It does not edit other cells, send email, or give a different answer on each recalculation. A component should behave the same way: props and state go in, JSX comes out.
Side effects during render
A side effect is anything a function does besides computing its return value. Writing to a variable outside the function is a side effect. So are changing an argument, sending a network request, and writing to the DOM.
Here is a component with a side effect in its body.
let guestCount = 0;
function Cup() {
// Side effect: changes a variable that exists outside this function.
guestCount = guestCount + 1;
return <h2>Tea cup for guest #{guestCount}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}The output depends on how many times React happened to call Cup before. With Strict Mode on in development, React calls each component twice, so the cups are numbered 2, 4, and 6. Without it you get 1, 2, and 3. A render that behaves differently depending on call history is not a calculation.
The fix is to pass the information in as a prop, so the output depends only on inputs.
function Cup({ guest }) {
return <h2>Tea cup for guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup guest={1} />
<Cup guest={2} />
<Cup guest={3} />
</>
);
}Now every call with guest={2} returns the same JSX, however often React calls it.
Common side effects in render code
| Code in the component body | Why it breaks purity | Where it belongs |
|---|---|---|
| Assigning to a module-level variable | Output depends on earlier calls | Props, state, or an event handler |
| `props.items.sort()` or `items.push(x)` on a prop | Mutates data the parent owns | Copy first, or compute a new array |
| `fetch(...)` or `localStorage.setItem(...)` | Runs on every call, including discarded ones | An event handler or an Effect |
| `document.title = ...` or `ref.current = ...` | Writes outside the returned JSX | An Effect, or an event handler |
| `Math.random()` or `Date.now()` used in the output | Same inputs give different output | State, an event handler, or `useId` for ids |
| `setSomeState(...)` called unconditionally | Triggers another render, which calls it again | An event handler |
Mutating props and state
The most common accidental violation is mutating something you were given. Sorting a prop looks harmless:
function SortedList({ items }) {
// Wrong: sort() changes the parent's array in place.
const sorted = items.sort();
return (
<ul>
{sorted.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}Array.prototype.sort reorders the array it is called on. The parent's array is now reordered too, and the parent may be showing that array elsewhere. Copy before you sort:
function SortedList({ items }) {
// Right: the spread creates a new array, so the prop is untouched.
const sorted = [...items].sort();
return (
<ul>
{sorted.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}Treat props and state as read-only snapshots. To "change" state, call its setter with a new value. Never edit the existing value in place.
Local mutation is fine
The rule is about things that existed before the render began. Variables you create during the call are yours to change.
function TagList({ tags }) {
// `visible` is created during this render, so mutating it is safe.
const visible = [];
for (const tag of tags) {
if (tag.length > 0) {
visible.push(tag);
}
}
return <p>{visible.join(', ')}</p>;
}Nothing outside this call can observe visible being built. Each call starts with a fresh array and returns the same result for the same tags. This is called local mutation, and it does not break purity.
How React helps you find impure code
React cannot detect every side effect, but Strict Mode catches many of them. In development, Strict Mode calls your component bodies a second time and discards the extra result. It does the same for functions you pass to useState, useMemo, and useReducer.
If the component is pure, the second call returns the same JSX and nobody notices. If it is impure, the two calls disagree. In the Cup example, the numbers jump by two. Treat a double-count, a duplicate request, or a flickering value in development as a prompt to look for a side effect in the render path.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import TeaSet from './TeaSet';
createRoot(document.getElementById('root')).render(
<StrictMode>
<TeaSet />
</StrictMode>
);Strict Mode does nothing in production builds, so it costs real users nothing.
Where side effects belong
Side effects are fine in React. They just do not belong in the body of the component. React gives you two places for them.
- Event handlers. These are functions you pass to props such as
onClickandonSubmit. React runs them only when the user does something, and never during render. Anything that happens because of a specific interaction goes here. - Effects. An Effect is a function passed to
useEffect. React runs it after the component has rendered and the screen has been updated. Use Effects for work that happens because the component is displayed, such as keeping a connection or subscription in sync.
The diagram shows where each piece of code runs.
The render step sits in the middle, and it is the only step React may repeat or discard. Event handlers and Effects run when React decides a change is real, so they can safely do work with consequences.
A request to a server shows the difference:
import { useState } from 'react';
function SaveButton({ draft }) {
const [status, setStatus] = useState('idle');
// Wrong place: this line would send a request on every render.
// post('/api/save', draft);
async function handleClick() {
setStatus('saving');
await post('/api/save', draft);
setStatus('saved');
}
return (
<button onClick={handleClick} disabled={status === 'saving'}>
{status === 'saved' ? 'Saved' : 'Save'}
</button>
);
}Here post stands for your own request helper. Because the call lives in handleClick, it runs once per click, however many times React renders SaveButton.
Why purity pays off
Purity is more than a style preference. It gives React and you real guarantees.
- React can skip and reorder work. Because a render has no external effects, React can render components in the order it prefers, pause low-priority renders, and drop renders that became outdated.
- Caching is safe. If the same inputs always give the same output, you can reuse the previous result. This is the idea behind
useMemo, which a later chapter covers. - Bugs are easier to reproduce. The screen is a function of props and state, so the same props and state give the same screen.
- Derived values need no storage. If output depends only on inputs, anything you can compute from props and state can be computed during render. The next chapter builds on this directly, replacing "state that mirrors other state" with a plain variable.
The last point is the main link to the rest of this tutorial. Many unnecessary Effects exist because the developer treated render as a place where nothing may be computed, so they added state and an Effect to sync it. Once you see render as a calculation, those Effects have no reason to exist.
Common mistakes
- Setting state in the render body. Calling
setCount(count + 1)unconditionally causes an immediate re-render, which calls it again, which loops until React stops with an error. React does allow a guarded state update during render in one narrow case. That case is covered in a later chapter. - Writing to a ref during render.
ref.current = valuein the body mutates something that outlives the render. Read refs in handlers and Effects. Writing during render is only acceptable for initializing a ref once, such asif (ref.current === null) ref.current = .... - Reading mutable outside values. Reading a module variable,
Date.now(), orwindow.innerWidthduring render makes the output depend on something React does not track. React will not re-render when that value changes. A later chapter showsuseSyncExternalStorefor exactly this. - Assuming render runs once. Code that only works if the body runs exactly once is a bug waiting for Strict Mode or concurrent rendering to expose it.
A quick checklist
When you read a component body, ask:
- Does it assign to anything declared outside the function, other than a variable created in this call?
- Does it call a method that mutates a prop, state value, or context value in place?
- Would calling it twice in a row with the same props and state produce a different result or leave a visible trace?
If any answer is yes, move that line into an event handler, or into an Effect if it must happen because the component is on screen. If the line was only computing a value, keep it in the render and make it work from props and state alone.
Exercise
This component renders a ranking list. Its parent also shows the same scores array in a chart, and the chart now appears in a different order after this component renders. Find the bug and fix it.
function Ranking({ scores }) {
const ranked = scores.sort((a, b) => b - a);
return <ol>{ranked.map(s => <li key={s}>{s}</li>)}</ol>;
}
Show answer
scores.sort(...) sorts the prop in place, so it mutates an array owned by the parent. That is a side effect during render. Copy the array first: const ranked = [...scores].sort((a, b) => b - a);. The prop is no longer changed, and the same scores always gives the same list.
Exercise
In development with Strict Mode, a component logs "Rendered" and increments a module-level renderCount once per render, and you see the count rise by two for every update. Is Strict Mode broken? What should you change if the count affects what is displayed?
Show answer
Strict Mode is working as designed. It calls the component body twice and discards one result to expose impure code. If the count appears in the output, the component depends on call history, which is a side effect in render. Remove the module-level counter from the render path and derive the displayed value from props or state. If you really need the count for debugging, keep it out of the returned JSX.
Exercise
Decide where each action should go, the render body, an event handler, or an Effect: (a) building a filtered copy of a list from props, (b) sending a form to the server when the user presses Submit, (c) updating document.title to match the current page prop.
Show answer
(a) The render body, because it is a pure calculation from props and needs no state. (b) An event handler, because the user's click causes it. (c) An Effect, because the browser title is an external system that must stay in sync with the displayed page, and writing to it during render would be a side effect.