Sub topic 1
Rendering should be pure
This chapter covers the rule that makes useEffect necessary: a component's render must be a pure calculation. You will see what purity means in React, how the render and commit phases differ, which mistakes break purity, and how to fix them.
Prerequisites
This chapter assumes you already know:
- How to write function components and JSX.
- How props and
useStatework, and that a state update schedules a re-render. - JavaScript closures, and the basics of Promises and
asyncfunctions. - Basic use of the browser DOM and
fetch.
You do not need to know useEffect yet. This chapter explains why it exists.
What "pure" means for a component
A pure function has two properties:
- Given the same inputs, it returns the same output.
- It changes nothing outside itself while it runs.
React treats your component function as a pure function of its props, state and context. The inputs are those three things. The output is the JSX the function returns. React calls the function, reads the JSX, and decides what the screen should look like.
function Greeting({ name }) {
const message = `Hello, ${name}!`;
return <h1>{message}</h1>;
}Greeting is pure. The same name always gives the same <h1>. Nothing outside the function is touched.
Now compare a component that breaks the rule:
let calls = 0;
function BadGreeting({ name }) {
calls = calls + 1; // mutates a variable outside the component
return <h1>Hello, {name}! (render #{calls})</h1>;
}The output depends on calls, which is not a prop, state or context value. The function also changes calls. Two renders with the same name can produce different output.
Why React requires purity
React does not promise to call your component exactly once per screen update. It may:
- Render a component, then throw the result away, for example when an update is interrupted by a more urgent one.
- Render a component more than once, for example in Strict Mode during development.
- Skip rendering a component when its inputs have not changed.
- Render a component without ever showing it on screen.
If rendering has side effects, any of these behaviors can duplicate, drop or reorder them. If rendering is pure, React can freely retry, pause or skip it, because nothing outside the calculation was affected.
Purity also makes components easier to reason about. You can read a component's output from its inputs alone, and you can test it by calling it with props and checking the result.
The render phase and the commit phase
React updates the screen in phases. The two that matter here are render and commit.
- Render phase. React calls your component functions and collects the JSX they return. This phase must be pure. React may repeat or discard it.
- Commit phase. React applies the needed changes to the DOM. It does this once for each committed render.
- Effects. After the commit, React runs effects. This is the place for code that reaches outside the component. The next chapters cover how.
Event handlers are a separate case. They are not part of rendering. They run in response to a user action, so they can change state, send requests and do other impure work.
Common ways to break purity
Mutating variables declared outside the component
The BadGreeting example above does this. A module-level counter, array or object that rendering modifies is shared across every render of every instance.
Mutating props or state
Props and state are read-only during rendering. Changing them in place hides the change from React.
import { useState } from 'react';
function BadList({ items }) {
items.push('extra'); // mutates a prop: every render adds another item
return (
<ul>
{items.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
);
}
function BadCounter() {
const [user, setUser] = useState({ visits: 0 });
user.visits += 1; // mutates state directly; React is not notified
return <p>{user.visits}</p>;
}To change state, call the setter with a new value. To show an extra item, build a new array:
function GoodList({ items }) {
const withExtra = [...items, 'extra']; // a new array; the prop is untouched
return (
<ul>
{withExtra.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}Reading values that change on their own
Math.random(), Date.now() and new Date() return a different value on each call. Using them directly in the returned JSX makes the output differ between renders with identical inputs.
function Clock() {
return <p>The time is {new Date().toLocaleTimeString()}</p>;
}This component shows the time of its last render, not the current time. It will not update by itself, and two renders in a row may disagree. A correct clock keeps the time in state and updates it from a timer, which is a side effect. Later chapters build that.
Doing work on the outside world during render
These all belong outside the render body:
- Calling
fetchor starting any network request. - Writing to
document.title,localStorageor other browser storage. - Calling
setTimeout,setIntervaloraddEventListener. - Writing to the DOM through a ref (reading refs during render is also discouraged).
- Logging to an analytics service.
import { useState } from 'react';
function BadProfile({ userId }) {
const [user, setUser] = useState(null);
// Runs on every render, and a state update triggers another render
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then(setUser);
return <p>{user ? user.name : 'Loading...'}</p>;
}This is worse than impure. The fetch resolves and calls setUser. That triggers a render, which starts another fetch, which calls setUser again. The result is an endless request loop.
Local mutation is allowed
Purity does not forbid changing values. It forbids changing values that existed before the render began. Variables you create inside the component function and discard at the end are fine to mutate:
function TagList({ tags }) {
const rows = []; // created during this render
for (const tag of tags) {
rows.push(<li key={tag}>{tag}</li>); // mutating a local value is fine
}
return <ul>{rows}</ul>;
}No other code can observe rows, so every render with the same tags gives the same result. This is called local mutation.
How Strict Mode helps you find impurity
In development, <StrictMode> calls your component function twice for each render and discards one result. If the component is pure, both calls return identical JSX and you see nothing unusual. If the component mutates an outside variable, you see the effect twice, such as a counter that jumps by two.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
let calls = 0;
function Counter() {
calls += 1; // impure on purpose
return <p>Render calls: {calls}</p>;
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<Counter />
</StrictMode>
);In development this typically shows 2 on the first render, not 1. Strict Mode is a detector for this class of bug, and it does nothing in production builds.
Where impure work goes instead
You have three places to put code that does something besides calculating JSX:
| Kind of work | Where it belongs | Example |
|---|---|---|
| Reaction to a user action | Event handler | Save a form when the button is clicked |
| Value computable from props or state | The render body itself | Filter a list by a search query |
| Synchronizing with something outside React because the component is on screen | An effect | Open a connection, subscribe, set `document.title` |
Event handlers cover most cases. Effects exist for the last row: work that must happen because the component was displayed or because its data changed, not because the user did something specific. That is the topic of the rest of this tutorial.
A checklist for pure rendering
- Compute the output only from props, state and context.
- Never modify props, state or variables that existed before the render.
- Do not call impure functions like
Math.random()ornew Date()in the output path. - Do not start requests, timers or subscriptions in the render body.
- Mutating values you create inside the render is fine.
- Update state by calling its setter with a new value, in an event handler or an effect, never in the render body itself.
Exercise
This component is meant to show a greeting and count how many times it was displayed. Name two ways it breaks the purity rule, and explain what goes wrong. let shown = 0; function Welcome({ names }) { shown += 1; names.sort(); return <p>Welcome {names.join(', ')} (shown {shown} times)</p>; }
Show answer
First, shown += 1 modifies a module-level variable that existed before the render. The output then depends on how many times React happened to call the function, which can be more than once per screen update (for example in Strict Mode), so the count is wrong. Second, names.sort() sorts the names prop in place, which mutates a prop. The parent's array changes without React knowing, and the data differs on later renders. Fix: copy before sorting, [...names].sort(), and keep a count in state or an effect, or remove it from rendering altogether.
Exercise
Why is it acceptable to build an array with push inside a component, while it is not acceptable to call items.push(...) on a prop?
Show answer
The array created inside the component is new on every render and nothing else can see it, so mutating it is local mutation and the result is the same for the same inputs. The prop array belongs to the parent and exists before the render, so mutating it changes data outside the calculation, and repeated renders keep changing it.