Sub topic 2
Rendering is a calculation, not a place for side effects
This chapter assumes you know function components, JSX, useState, props, and the basics of useEffect with a dependency array. It covers the idea that later chapters build on: rendering must be a pure calculation.
What "pure" means for a component
React calls your component function to find out what the screen should look like. The inputs are props and state. The output is JSX. A pure component returns the same JSX every time it gets the same props and state. It also changes nothing outside itself while it runs.
This matters for three reasons:
- React may call your component more than once before it commits anything to the screen. In development, Strict Mode does this on purpose to expose impure code.
- React may start a render and then throw it away, for example when newer state arrives.
- React can skip a render entirely when nothing it depends on has changed.
If rendering has side effects, any of these behaviors can make them run twice, run at the wrong time, or never run.
What counts as a side effect
A side effect is anything that reaches outside the calculation. Common examples:
- Sending a network request
- Writing to
localStorageordocument.title - Starting a timer or subscribing to an event
- Changing a variable that was created before the render started
Reading props and state is fine. Creating new values inside the function is fine. Changing something that existed before the render began is not.
let renderCount = 0;
// Impure: it changes a variable outside the component.
function Counter() {
renderCount = renderCount + 1;
return <p>Rendered {renderCount} times</p>;
}The output of Counter depends on how many times React happened to call it. Under Strict Mode in development, it would count two calls per render.
A pure version keeps everything it changes local:
function Greeting({ name }) {
// Local values are fine. They are created fresh on every render.
const items = [];
items.push('Hello');
items.push(name);
return <p>{items.join(', ')}</p>;
}Mutating items is safe because it was created during this render and nothing else can see it.
Where side effects go instead
Side effects still have a home. React gives you two places that run outside the calculation:
- Event handlers. They run when the user does something, such as a click or a form submit. They are not part of rendering, so they can do anything.
- Effects. They run after React has committed the render to the screen. They are for work that must stay in sync with an outside system.
The flow looks like this:
The arrows from the Effect and the event handler back to "Props and state" show how a new render begins. Rendering never starts side effects itself. It only reports what the screen should show.
A common mistake: fixing impurity with an Effect
Once you know that rendering must be pure, it is tempting to move every calculation into an Effect. That swaps one problem for another. Consider this component:
import { useState, useEffect } from 'react';
function Cart({ items }) {
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);
return <p>Total: {total}</p>;
}Nothing here is impure. Summing prices is a pure calculation, so it belongs in render. Putting it in an Effect forces React to render with a stale total, run the Effect, set state, and render again. The next chapter shows the fix: compute the value directly in the component body.
A useful test is to ask what caused the work. If the answer is "the data changed and I need to display something based on it," that is a rendering calculation. If the answer is "the user did something," use an event handler. If the answer is "the component appeared and must connect to something outside React," use an Effect.
Summary of the rule
- Render reads props and state and returns JSX.
- Render may create and change local values.
- Render must not change anything that existed before it started.
- Work that is not a calculation goes in an event handler or an Effect.
Exercise
This component sets document.title directly in its body. Why is that a problem, and where could the line go instead?
function Page({ title }) {
document.title = title;
return <h1>{title}</h1>;
}
Show answer
Writing to document.title changes something outside the component, so render is no longer pure. React may call or discard a render without committing it, so the title could change for a render that never reaches the screen. Because this is synchronizing with a system outside React (the browser document), it belongs in an Effect: useEffect(() => { document.title = title; }, [title]);.
Exercise
A component declares const list = [] in its body, then calls list.push(item) for each prop item and renders the list. Is this pure?
Show answer
Yes. The array is created during this render and nothing outside the component can see it, so changing it is safe. Each render builds a fresh array from the same props, giving the same output.