Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.4 — Why StrictMode Runs Effects Twice
React · Example 1 of 4

StrictMode: render twice, then connect, disconnect, connect

This example uses <StrictMode> on purpose. The render is logged twice, and the effect runs setup → cleanup → setup. Because the cleanup undoes the setup, the app ends with exactly one connection, as in production.

In development only, <StrictMode> renders every component twice and runs every effect setup → cleanup → setup when it first mounts, so missing cleanups and impure renders show up immediately; the fix is always to make the effect symmetric, never to stop it running twice.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

This component ticks twice as fast in development. Fix it: ``jsx function Clock() { const [s, setS] = useState(0); useEffect(() => { setInterval(() => setS((x) => x + 1), 1000); }, []); return <p>{s}</p>; }

02

Write a Subscriber that calls store.subscribe(fn) (which returns an unsubscribe function) and survives StrictMode.

Explain it without notes

01

What exactly does StrictMode do in development, and what does it do in production?

02

Why does React run effects setup → cleanup → setup in StrictMode? What bugs does it catch?

03

Why is a useRef guard the wrong fix for an effect that runs twice?

04

Your data fetch fires twice in development. Is that a problem? How do you make it correct?

StrictMode: render twice, then connect, disconnect, connect

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render ChatRoom
render ChatRoom
connect to general | open connections: 1
disconnect from general | open connections: 0
connect to general | open connections: 1