Sub topic 11
Strict Mode and why render functions must be pure
This chapter assumes you know JavaScript functions, basic React components and props, and the useState hook. You should also know that React calls your component function during the render phase, before it updates the DOM.
Why purity matters
A pure render function returns the same JSX for the same props and state. It also changes nothing outside itself while it runs. React relies on this. It may call a component more than once, pause a render, throw it away, or restart it. If rendering has side effects, those repeated calls produce visible bugs.
Strict Mode is a development-only tool that helps you find these bugs. It adds no UI and has no effect in production builds.
Turning Strict Mode on
Wrap your app in <StrictMode>:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);In development, Strict Mode does two things that matter for this chapter:
- It calls component functions, state initializers, and updater functions twice per render. React uses one result and discards the other.
- It runs each effect's setup, then cleanup, then setup again, once, when a component first mounts.
The double render is how it detects impure rendering. A pure function gives the same result both times, so you see no difference. An impure function behaves differently on the second call, and the bug shows up.
Spotting an impure render
This component changes a variable that lives outside it:
let guestCount = 0;
function Guest() {
guestCount = guestCount + 1;
return <p>Guest #{guestCount}</p>;
}
export default function Party() {
return (
<>
<Guest />
<Guest />
<Guest />
</>
);
}You expect guests 1, 2, 3. In Strict Mode you will see higher numbers, because each Guest ran twice and mutated guestCount both times. The result also changes on every re-render.
The fix is to pass data in through props:
function Guest({ number }) {
return <p>Guest #{number}</p>;
}
export default function Party() {
return (
<>
<Guest number={1} />
<Guest number={2} />
<Guest number={3} />
</>
);
}What counts as a side effect in render
| Impure pattern in render | Why it breaks | Where it belongs |
|---|---|---|
| Changing a variable declared outside the component | Repeated renders accumulate changes | Compute from props and state instead |
| Mutating props or state objects | Other code and later renders see changed data | Copy first, then call the setter |
| Reading `Math.random()` or `Date.now()` | Output differs between calls | State, or an effect |
| Fetching data or setting timers | Runs on every discarded render | `useEffect` or an event handler |
| Writing to the DOM directly | Render may never commit | A ref in an effect |
Creating and changing variables that are local to the render is fine. A new array built inside the component and filled during the same call is pure, because nothing outside can observe it.
function TagList({ tags }) {
const items = [];
for (const tag of tags) {
items.push(<li key={tag}>{tag}</li>);
}
return <ul>{items}</ul>;
}The effect double-run
On mount, Strict Mode runs setup, cleanup, and setup again. This checks that your cleanup truly reverses your setup.
import { useEffect } from 'react';
function Ticker() {
useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(id);
}, []);
return <p>Check the console</p>;
}Without the clearInterval cleanup, the extra mount would leave two intervals running. Strict Mode makes that leak visible right away instead of after a user navigates around.
How this fits the rendering model
Only the render phase is double-called. The commit phase happens once.
Exercise
A component does items.push(newItem) on a items array it received as a prop, then returns a list. In Strict Mode, the list shows each new item twice. Why, and how do you fix it?
Show answer
The render mutates the prop, and Strict Mode calls the component twice, so the push runs twice on the same array. Render must not mutate props. Instead, build a new array such as [...items, newItem] and render that, or add the item in an event handler that calls a state setter.
Exercise
Your effect opens a WebSocket on mount and has no cleanup. What do you see in Strict Mode, and what is the fix?
Show answer
Two connections open, because setup runs, cleanup (none) runs, and setup runs again. Return a cleanup function from the effect that closes the socket, for example return () => socket.close();.