Sub topic 11
Strict Mode and Why Render Functions Must Be Pure
This chapter assumes you know JavaScript functions, objects, and arrays, basic React components and JSX, and the useState hook. It also assumes you have read the earlier chapters on rendering as a pure calculation and on effects timing. Here you will see how StrictMode turns purity violations into visible bugs during development, and how to fix the ones it finds.
What purity means for a component
React expects a component function to behave like a mathematical function. Given the same props, state, and context, it returns the same JSX. It also does nothing observable while it runs. Two rules follow from this:
- A component must not change anything that existed before it started rendering. It may create and change new objects and arrays that it builds during the call (a "local mutation"). It must not change props, state, or variables declared outside the function.
- A component must not depend on anything that changes between calls without React knowing about it, such as
Math.random(),Date.now(), or a counter kept in a module-level variable.
Side effects such as network requests, subscriptions, timers, and DOM changes belong in event handlers or in effects. They do not belong in the body of the component.
React relies on this contract. It may call your component more than once for a single screen update, throw away a render result, pause a render, or restart it. These behaviors are only safe if rendering has no side effects. If rendering is pure, calling it twice gives the same answer and nobody notices. If it is not, the extra calls expose the problem.
What StrictMode does
StrictMode is a component you wrap around part of your tree. It adds extra checks in development only. It has no UI and produces no output in a production build.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);Everything inside the wrapper is checked, including all descendants. You can wrap only one subtree if you want to adopt it gradually.
In development, StrictMode does these things:
- It renders each component an extra time to find impurities. React calls component bodies,
useStateanduseReducerinitializer functions, updater functions, anduseMemocallbacks twice. - It runs an extra mount cycle for effects. After a component mounts, React runs the effect setup, then the cleanup, then the setup again, to simulate a component being unmounted and remounted.
- It runs an extra cycle for ref callbacks (in React 19) to check that ref cleanup is correct.
- It reports use of deprecated APIs.
The exact list grows between React versions, so check the documentation for the version you use.
The double render
The extra render has a specific purpose. If a function is pure, calling it twice with the same inputs gives the same result and changes nothing. If the two calls differ, or if the second call damages something, the component has a side effect in render.
React uses the result of one call and discards the other. In recent versions, it also silences console.log output from the second call, which is dimmed in the browser console in React DevTools or hidden entirely depending on settings. This means a log line may appear once or twice depending on your tooling. Do not depend on a count of log lines to reason about how many renders happened.
The double render does not mean your component renders twice for the user. It happens only in development, and only to help you find bugs.
A bug the double render exposes
This component keeps a counter in a module variable and uses it to number items:
let nextNumber = 0;
function Badge() {
nextNumber = nextNumber + 1; // mutates a variable outside the component
return <span>#{nextNumber}</span>;
}
export default function App() {
return (
<>
<Badge />
<Badge />
<Badge />
</>
);
}In production, this shows #1, #2, #3 on first load. In StrictMode, each Badge is called twice and only one result is kept, so the numbers skip: you see something like #2, #4, #6. The numbers also keep growing every time a Badge re-renders. The result depends on how often React calls the function, and that is exactly what React does not promise.
The fix is to pass the value in, so the output depends only on props:
function Badge({ number }) {
return <span>#{number}</span>;
}
export default function App() {
return (
<>
<Badge number={1} />
<Badge number={2} />
<Badge number={3} />
</>
);
}Mutating props or state
A common impurity is changing an object that came from props or state. The double render makes this visible because the second call sees the first call's change.
function Cart({ items }) {
items.push({ id: 'tax', price: 5 }); // mutates the prop
const total = items.reduce((sum, item) => sum + item.price, 0);
return <p>Total: {total}</p>;
}Each render adds another tax item, so the total grows. The fix is to copy first:
function Cart({ items }) {
const withTax = [...items, { id: 'tax', price: 5 }];
const total = withTax.reduce((sum, item) => sum + item.price, 0);
return <p>Total: {total}</p>;
}Here withTax is a local value created during the render, so changing or building it is safe. Mutating items is not.
Reading values that change on their own
Date.now(), Math.random(), and new Date() return different values on every call. Using them directly in the returned JSX makes two renders disagree:
function Greeting() {
const id = Math.random(); // differs on every call
return <p data-id={id}>Hello</p>;
}If you need a value that is stable across renders, store it in state with a lazy initializer, or use useId for identifiers:
import { useId, useState } from 'react';
function Greeting() {
const id = useId();
const [createdAt] = useState(() => Date.now());
return (
<p id={id} data-created={createdAt}>
Hello
</p>
);
}React calls the useState initializer twice in StrictMode, but keeps only one result, so the stored value stays consistent.
What is allowed in render
Purity does not mean a component can do nothing. These are fine:
- Reading props, state, and context.
- Creating new local variables, arrays, and objects, and changing them before returning.
- Calling other pure functions.
- Reading a ref's
.currentonly during initialization. In general, avoid reading or writingref.currentin render.
Side effects go elsewhere:
| Work | Where it belongs |
|---|---|
| Responding to a click or input | Event handler |
| Fetching data, subscribing, timers | Effect (`useEffect`) |
| Changing the DOM directly | Effect or ref callback |
| Computing a value from props and state | Render, optionally with `useMemo` |
| Adjusting state when a prop changes | Render (carefully) or a `key` |
The double effect
The second check applies to effects. After the first mount, StrictMode runs this sequence in development:
- Setup runs.
- Cleanup runs.
- Setup runs again.
This simulates a user leaving a screen and coming back. React does this because it plans features that keep state while hiding and showing UI, and an effect must survive that. If your cleanup does not fully undo your setup, the extra cycle exposes a leak.
import { useEffect } from 'react';
function Ticker() {
useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
// Missing cleanup: two intervals run after StrictMode's extra cycle
}, []);
return <p>Ticking</p>;
}After the extra cycle, two intervals run, and you see tick printed twice per second. The fix is to return a cleanup function:
import { useEffect } from 'react';
function Ticker() {
useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(id);
}, []);
return <p>Ticking</p>;
}Now setup, cleanup, setup leaves exactly one running interval, which matches the behavior of a real unmount and remount.
Common mistakes when reacting to StrictMode
- Removing StrictMode to make the problem go away. The double behavior is a report of a real bug. Without it, the bug usually still appears later, for example under concurrent rendering or when a component remounts.
- Using a ref to skip the second effect. A guard such as
if (didRun.current) return;hides the symptom but leaves the code incorrect. Write cleanup that makes setup safe to repeat. - Counting renders from logs. Silenced second-call logs make counts unreliable. Use the Profiler to measure real renders.
- Fetching data in an effect without handling repeats. The second setup sends the request again. Ignore stale responses with a flag set in cleanup, or use a data library that handles it.
A fetch effect that handles the repeat looks like this:
import { useEffect, useState } from 'react';
function User({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
if (!ignore) setUser(data);
});
return () => {
ignore = true;
};
}, [userId]);
return <p>{user ? user.name : 'Loading...'}</p>;
}The first request is marked ignored by the cleanup, so only the second request sets state. The duplicate network call still happens in development. That is expected, and production makes only one.
Why this matters beyond development
Purity is what lets React work flexibly. Rendering can be paused, restarted, or abandoned when a more urgent update arrives, as you will see in the chapter on concurrent rendering. A render may start and never reach the commit phase. Any side effect done during that render would have happened for a screen the user never saw. Keeping render pure means these discarded renders cost only time and leave no trace.
Exercise
This component is wrapped in StrictMode. In development the displayed list shows the "Draft" entry twice. Explain why, and rewrite the component so it shows one entry. function Names({ names }) { names.push('Draft'); return <ul>{names.map(n => <li key={n}>{n}</li>)}</ul>; }
Show answer
The component mutates its names prop during render. StrictMode calls the function twice with the same array, so the second call sees the item pushed by the first and pushes another. Even without StrictMode, every re-render would add another entry. Copy the array instead of changing it:
function Names({ names }) {
const all = [...names, 'Draft'];
return <ul>{all.map((n, i) => <li key={n + i}>{n}</li>)}</ul>;
}
The new array is created during the render, so changing or extending it is safe, and the prop is left untouched. (The key here combines name and index only because "Draft" could duplicate an existing name; with unique IDs, use those instead.)
Exercise
A component starts a WebSocket connection in useEffect and never closes it. In StrictMode development, the server reports two open connections after the page loads. What causes this, and how do you fix it?
Show answer
StrictMode runs setup, cleanup, setup on mount. Because the effect returns no cleanup, the first connection is never closed, so two connections stay open. Return a cleanup function that closes the socket, for example const ws = new WebSocket(url); return () => ws.close();. Then the cleanup closes the first connection before the second setup runs, leaving one open connection, which is the same as the result of a real unmount and remount.