Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readReact
#React#Debugging#Best Practices
3D illustration of development-mode double render and mount-remount diagnostic probes detecting missing effect cleanups

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

tsx
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:

js
// 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:

tsx
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 state

ref.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

BehaviourDevelopment + StrictModeProduction
Component renderTwice per render passOnce
useState updater / reducerInvoked twiceOnce
Effect on mountSetup, cleanup, setupSetup
Ref callback on mountCalled twiceOnce
Class componentDidMountCalled, unmounted, called againOnce
Warning for impure renderSurfaces as mismatched outputSilent
Warning for missing cleanupDuplicate listener or requestSilent until it bites
Double-invocation of useMemoPossibleNo
Effect on dependency changeSetup/cleanup as usualSetup/cleanup as usual

Practical Edge Cases & Deep Dives

1. Impure render caught by the second pass

tsx
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.

tsx
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

tsx
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

tsx
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

tsx
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

tsx
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

tsx
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

SymptomCauseFix
Console shows two rendersStrictMode development passExpected; verify the output is identical
Duplicate network requests in developmentEffect without cleanupAbortController or an ignore flag
Two WebSocket connectionsMissing close() in cleanupReturn a cleanup that closes it
Interval runs twiceNo clearIntervalClear in the cleanup
Warning about findDOMNodeClass component with string refsUse refs directly
State resets on navigation in development onlyCleanup dispatches a resetReset explicitly, not via remount
Analytics fired twice in developmentImpure reducer or renderMove the call into the handler
Random value differs between passesMath.random() in renderLazy initialiser or server-generated id
Double subscription in a librarysubscribe returns nothingReturn an unsubscribe function
"Cannot update a component while rendering"setState called during renderMove 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 tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.