React StrictMode: Why Components Render Twice and Impure Side-Effect Detection
Double render, double Effect setup and double reducer calls are diagnostics, not bugs. What each one detects and how to fix the code it catches.

Quick Summary
StrictMode is a development-only wrapper that makes React hostile to impure code. In development it renders every component twice, runs Effects with a setup/cleanup/setup cycle on mount, double-invokes reducers and state updater functions, and re-runs ref callbacks — all to surface the defects that a production build would hide until a user hit them. Nothing about it changes production behaviour: the same component, without the wrapper, renders once and mounts once.
The double render exists to catch impurity. If a component computes Math.random() or Date.now() during render, the two calls produce different values and React can show you that the output is not a function of props and state. If an Effect subscribes without cleaning up, the second setup reveals a duplicated listener, socket, or interval. These are the bugs that later become "the chat connects twice after a hot reload" or "the counter increments by two".
The correct response to a StrictMode warning is almost never to remove the wrapper or to guard with a module-level "did I already run" flag. It is to make the render pure and the Effect symmetric, which is also what makes a component survive being mounted, unmounted, and remounted — the behaviour React relies on for Suspense, Offscreen, and Fast Refresh.
Basic Syntax & Signature
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);The wrapper renders nothing and takes only children. In Next.js it is enabled through the config rather than by wrapping the app manually:
// next.config.js
module.exports = {
reactStrictMode: true, // default in the App Router
};The development-only lifecycle is what the name refers to, and it is worth writing out because the log order confuses people the first time:
function Probe() {
const ref = useRef(0);
ref.current += 1; // render-phase mutation: flagged by StrictMode's second pass
console.log("render", ref.current);
useEffect(() => {
console.log("effect setup");
const id = setInterval(() => {}, 1000);
return () => {
console.log("effect cleanup");
clearInterval(id);
};
}, []);
return <p>probe</p>;
}
// Development output:
// render 1
// render 2 <- second render of the same mount
// effect setup
// effect cleanup <- simulated unmount
// effect setup <- real mount, reusing stateref.current is 2 after mount because the render body ran twice in the same mount. That value is a bug indicator, not a React quirk: a ref written during render is a side effect in a place that must be pure.
Key Comparison Table
| Behaviour | Development + StrictMode | Production |
|---|---|---|
| Component render | Twice per render pass | Once |
useState updater / reducer | Invoked twice | Once |
| Effect on mount | Setup, cleanup, setup | Setup |
| Ref callback on mount | Called twice | Once |
Class componentDidMount | Called, unmounted, called again | Once |
| Warning for impure render | Surfaces as mismatched output | Silent |
| Warning for missing cleanup | Duplicate listener or request | Silent until it bites |
Double-invocation of useMemo | Possible | No |
| Effect on dependency change | Setup/cleanup as usual | Setup/cleanup as usual |
Practical Edge Cases & Deep Dives
1. Impure render caught by the second pass
function OrderSummary({ items }: { items: Item[] }) {
// Wrong: a new id on every render pass; StrictMode renders twice,
// so the value logged in development differs from what is committed.
const orderId = useMemo(() => `order-${Math.random().toString(36).slice(2)}`, []);
return <p>{orderId} · {items.length} items</p>;
}useMemo is not a guarantee: React may discard a memo cache, and StrictMode's second render is one of the moments it does. The fix is to derive the id from data on the server, or to create it in an event handler and store it in state — both put randomness in a place that runs once by design.
function OrderSummaryFixed({ items }: { items: Item[] }) {
const [orderId] = useState(() => crypto.randomUUID()); // lazy initialiser: runs once per mount
return <p>{orderId} · {items.length} items</p>;
}2. Effects that were never symmetric
function ChatRoom({ roomId }: { roomId: string }) {
const [messages, setMessages] = useState<string[]>([]);
useEffect(() => {
const socket = new WebSocket(`wss://example.com/rooms/${roomId}`);
socket.onmessage = (event) => setMessages((m) => [...m, event.data]);
// Missing: return () => socket.close();
}, [roomId]);
return <ul>{messages.map((m) => <li key={m}>{m}</li>)}</ul>;
}In production with a single mount, this looks fine. Under StrictMode the setup runs twice, so two sockets connect and every message arrives twice. The correct form returns a cleanup, and the payoff is not just the warning: it is that the component reconnects properly when roomId changes.
3. Fetching twice on mount
function Profile({ userId }: { userId: string }) {
const [data, setData] = useState<Profile | null>(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((r) => r.json())
.then(setData)
.catch((e) => {
if (e.name !== "AbortError") throw e;
});
return () => controller.abort();
}, [userId]);
return data ? <p>{data.name}</p> : <p>Loading…</p>;
}Two requests appear in the network panel in development and one in production. Without the AbortController, the cleanup does nothing and the aborted request's late response can still call setData out of order — a race that shows up as the previous user's profile flashing after navigating.
4. Reducers and updaters must be pure
function Cart() {
const [items, dispatch] = useReducer((state: Item[], action: Action) => {
if (action.type === "add") {
// Wrong under StrictMode: the reducer runs twice, so this fires twice.
analytics.track("cart_add", action.item.id);
return [...state, action.item];
}
return state;
}, []);
return <button onClick={() => dispatch({ type: "add", item: { id: "x", qty: 1 } })}>add</button>;
}Reducers and updater functions are called twice in development because they must be pure. Analytics, logging, and DOM writes belong in the event handler that dispatches the action, or in an Effect that reacts to the committed state.
5. The "did I already run" flag anti-pattern
let didInit = false; // module-level flag: the wrong fix
function App() {
useEffect(() => {
if (didInit) return;
didInit = true;
loadAnalytics(); // now runs once — and never again after Fast Refresh
}, []);
return null;
}This silences the symptom and breaks the semantics. Effects are supposed to be re-runnable, and anything they start must be stoppable. For third-party scripts that genuinely cannot be loaded twice, the correct shape is a module-level singleton that tracks its own promise, plus an Effect that is safe to call repeatedly — not a flag that turns the second mount into a no-op and leaves the first mount's resource attached to a dead tree.
6. StrictMode and state that must survive remounting
function Editor() {
const [draft, setDraft] = useState(() => readDraftFromStorage());
useEffect(() => {
const id = setTimeout(() => writeDraftToStorage(draft), 500);
return () => clearTimeout(id);
}, [draft]);
return <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />;
}On a StrictMode remount, state is preserved — React keeps the fiber's hooks across the simulated unmount because the component did not actually leave the tree. That is the "reusable state" property React needs to add and remove UI without losing user input. Code that relies on a remount to reset state, such as a cleanup that dispatches a "reset" action, will find the state still there and must express the reset explicitly.
Common Compilation/Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Console shows two renders | StrictMode development pass | Expected; verify the output is identical |
| Duplicate network requests in development | Effect without cleanup | AbortController or an ignore flag |
| Two WebSocket connections | Missing close() in cleanup | Return a cleanup that closes it |
| Interval runs twice | No clearInterval | Clear in the cleanup |
Warning about findDOMNode | Class component with string refs | Use refs directly |
| State resets on navigation in development only | Cleanup dispatches a reset | Reset explicitly, not via remount |
| Analytics fired twice in development | Impure reducer or render | Move the call into the handler |
| Random value differs between passes | Math.random() in render | Lazy initialiser or server-generated id |
| Double subscription in a library | subscribe returns nothing | Return an unsubscribe function |
| "Cannot update a component while rendering" | setState called during render | Move it into an effect or handler |
StrictMode is best read as a second opinion from the compiler's future self: it enforces the rules that concurrent features, Suspense, and Fast Refresh assume. A codebase that runs clean under it is a codebase where a component can be interrupted, discarded, and re-run without corrupting anything — which is what React has been increasingly asking of components since React 18.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
React with TypeScript: Generic Components, PropsWithChildren, and Event Types
Generic props that infer from data, PropsWithChildren instead of React.FC, and element-scoped event types that keep currentTarget typed.
React useTransition and useDeferredValue: Non-Blocking Concurrent UI Updates
Transitions let React throw away background work when typing arrives. Which hook defers what, and why a controlled input must never be transitioned.
React.lazy and Code Splitting: Route Chunks, Preloading, and Suspense
Where the split points belong, how to preload on intent, and how to recover when a stale chunk 404s after a deployment.
More in React
All React guidesThe guides filed next to this one in React, in library order.