Sub topic 12
Why effects run twice in development
This chapter assumes you know useEffect syntax, the dependency array, and cleanup functions from the earlier chapters. You should also be comfortable with closures and with how React renders and commits.
You add a console.log inside an effect with an empty dependency array. It prints twice. You search for the cause and find that your app is wrapped in <StrictMode>. This is deliberate. This chapter explains what React does, why it does it, and how to write effects that behave correctly when it happens.
What Strict Mode does
<StrictMode> is a development-only wrapper. It adds extra checks to the components inside it. It does nothing in a production build, so your users never see the double run.
Since React 18, Strict Mode does the following to every component the first time it mounts:
- React runs the effect's setup function.
- React immediately runs its cleanup function, as if the component had unmounted.
- React runs the setup function again, as if the component had mounted again.
The sequence is setup, cleanup, setup. It happens once per mount. Later re-renders caused by changed dependencies run the normal cleanup-then-setup pair and are not doubled.
The component's state and DOM nodes are kept during the simulated remount. Only effects are torn down and set up again.
Strict Mode also repeats other work
Effects are not the only thing it repeats. It also calls some functions twice to expose impure code.
| What is called | Extra call in development | What it catches |
|---|---|---|
| Component function body | Rendered twice | Mutating variables or props during render |
| `useState` initializer, `useMemo` and `useReducer` functions | Called twice | Side effects inside calculations |
| State updater functions such as `setX(x => ...)` | Called twice | Updaters that mutate or have side effects |
| Effect setup and cleanup | Setup, cleanup, setup on mount | Missing or incorrect cleanup |
| Ref callbacks (React 19) | Detach and attach again on mount | Refs that are not released |
React uses the result of one call and ignores the other. If your output differs between the two calls, the code is impure. This ties back to the first chapter on pure rendering.
Why React does this
An effect should synchronize your component with something outside React, and that synchronization should be reversible. A correct effect can be started, stopped, and started again with the same result. If an effect breaks when it is stopped and restarted, it has a bug.
The bug usually does not show up in a simple demo, but it shows up in real use. A user navigates away and back. Fast Refresh reloads a component while you edit it. A future React feature, such as hiding a subtree and showing it later while keeping its state, unmounts and remounts effects without destroying state. Strict Mode forces this lifecycle to happen on every mount, so you find the problem while developing and not in production.
A leak that Strict Mode exposes
This effect has no cleanup:
import { useEffect } from 'react';
function createConnection(roomId) {
return {
connect() {
console.log(`Connecting to ${roomId}`);
},
disconnect() {
console.log(`Disconnected from ${roomId}`);
},
};
}
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
// Bug: nothing closes the connection.
}, [roomId]);
return <h1>Room: {roomId}</h1>;
}In development the console shows two connections and no disconnect:
Connecting to general
Connecting to generalThe doubled log is the symptom. The real problem is that the first connection is still open. In production this leaks a connection whenever the user switches rooms or leaves the page. Adding the cleanup fixes it:
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);The console now shows:
Connecting to general
Disconnected from general
Connecting to generalEach connect has a matching disconnect, and one connection stays open. That is the correct final state.
Do not suppress the second run
Many developers respond by stopping the double run. The most common attempt is a ref that remembers whether the effect already ran:
import { useEffect, useRef } from 'react';
function ChatRoom({ roomId }) {
const didRun = useRef(false);
useEffect(() => {
if (didRun.current) return; // Do not do this
didRun.current = true;
const connection = createConnection(roomId);
connection.connect();
}, [roomId]);
return <h1>Room: {roomId}</h1>;
}This hides the symptom and keeps the bug. The effect still never disconnects. When roomId changes, the ref is already true, so the effect does not reconnect to the new room. Removing <StrictMode> has the same problem: it silences the check without fixing the code. Fix the effect by making it reversible.
Common cases
Data fetching
A fetch effect sends two requests in development. This is harmless if you abort the first one, as in the earlier data-fetching chapter:
import { useEffect, useState } from 'react';
function User({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => res.json())
.then(setUser)
.catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [userId]);
return user ? <h1>{user.name}</h1> : <p>Loading...</p>;
}Two requests appear in the network tab. The first one is cancelled and only the second one updates state. Do not try to prevent the second request. In production, the abort protects you when userId changes quickly. If you want to avoid duplicate requests, use a data library that caches them, not a hand-written guard in the effect.
Timers and listeners
Timers and event listeners are reversible, so the cleanup from earlier chapters is enough. Without clearInterval, you get two intervals running and the counter advances twice per second. The doubled speed is how that bug looks in development.
Analytics and one-time actions
Some code should not run twice, such as a purchase request or a page-view event. Ask what the code is for.
- If it runs because the user did something, such as clicking Buy, it belongs in an event handler. Event handlers are not doubled.
- If it runs because the component appeared on screen, such as a page view, it is a real effect. A duplicate log in development is acceptable, because production runs it once.
- If it runs once per application start, such as loading a token from storage, it does not belong to any one component. Run it at module level, or outside React, before rendering:
import { createRoot } from 'react-dom/client';
import { StrictMode } from 'react';
function App() {
return <h1>My app</h1>;
}
function initApp() {
if (typeof window !== 'undefined') {
console.log('App initialized');
}
}
initApp();
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);How to test an effect yourself
You can check for this class of bug without Strict Mode. Mentally run your effect as setup, cleanup, setup. Then ask:
- After the cleanup, is everything the setup created gone (listeners, timers, connections, subscriptions, DOM changes)?
- After the second setup, is the state the same as after a single setup?
- Does the cleanup undo only this effect's work, and not something shared with other components?
If a cleanup is hard to write, such as undoing a network write, the code is probably an event handler or belongs outside React.
Summary of what to remember
- The double run is development-only and happens once per mount.
- It is a test of your cleanup, not a React bug.
- The right fix is a correct cleanup, not a ref guard or removing
<StrictMode>. - Anything that must happen once because of a user action belongs in an event handler. Anything that must happen once per app start belongs outside components.
Exercise
An effect opens a WebSocket in a component and has an empty dependency array, but no cleanup function. In development the server logs two connections when the page loads. A teammate proposes adding useRef so the effect skips its second run. Explain what is wrong with that fix and write the correct one.
Show answer
The two connections show that the first is never closed, because there is no cleanup. A ref guard hides the log but the leak remains: the socket is never closed on unmount and the effect cannot reconnect if its inputs change. The correct fix is to return a cleanup function that closes the socket: useEffect(() => { const ws = new WebSocket(url); return () => ws.close(); }, [url]);. In development the server then logs connect, close, connect. In production it logs one connection.
Exercise
List the order of calls React makes for an effect on first mount in development with Strict Mode, and say what changes in a production build.
Show answer
Setup, cleanup, setup. In production only the first setup runs on mount. Cleanup runs later, when dependencies change or the component unmounts.