Sub topic 7
Why effects run twice in development
This chapter assumes you can write a component that fetches inside useEffect and that you know how the dependency array and effect cleanup work. If you have seen two identical requests in your browser's Network tab and wondered whether your code is broken, this chapter explains it.
What you see
Open a project created with a current React template and add an effect that logs:
import { StrictMode, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
function Demo() {
useEffect(() => {
console.log('effect: start');
return () => console.log('effect: cleanup');
}, []);
return <p>Check the console</p>;
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<Demo />
</StrictMode>
);In development the console prints this:
effect: start
effect: cleanup
effect: startThe component mounted once, yet the effect ran, was cleaned up, and ran again. In a production build you get only the first line.
What Strict Mode does
<StrictMode> is a development-only wrapper. When a component inside it mounts for the first time, React does the following:
- Renders the component and commits it to the screen.
- Runs the effect setup.
- Immediately runs the effect cleanup, as if the component had been unmounted.
- Runs the effect setup again.
The extra cycle happens once per mount, not on every re-render. It applies to every effect in the tree, including effects inside libraries you use.
React also double-invokes some code that is not an effect. Component function bodies, state initializer functions, and reducers run twice in development, so React can detect impure code. This is a separate check from the effect cycle, and the fix is different: keep render logic free of side effects.
Why React does this
React wants every effect to be symmetrical. Setup starts something, and cleanup stops it, so running the pair repeatedly leaves the app in the same state as running setup once.
That property matters in production too. React is built so that a component can be hidden and shown again while keeping its state, and a user can navigate away and back. In those cases React may run your cleanup and setup again on a component that never really went away. An effect that only works when it runs exactly once will break in these situations, often in ways that are hard to reproduce.
Strict Mode makes the problem show up on every mount, on your machine, while you are still writing the code. The question it asks is: "If this effect ran, stopped, and ran again, would the app still behave correctly?"
A bug that Strict Mode reveals
An effect without cleanup leaks. This one starts an interval and never stops it:
import { useEffect, useState } from 'react';
function Ticker() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
setInterval(() => setSeconds((s) => s + 1), 1000);
}, []);
return <p>{seconds}</p>;
}In development, two intervals are running, so the counter goes up by two each second. The bug exists in production too. It is just easier to miss there, for example when the component unmounts and the interval keeps updating state that nobody displays. The fix is cleanup:
import { useEffect, useState } from 'react';
function Ticker() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds}</p>;
}Now the simulated unmount clears the first interval, and the counter ticks once per second.
What it means for fetching
A fetch effect is a good example, because the "something started" is an in-flight request. Here is the component from the earlier chapters with abort cleanup:
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
setIsLoading(true);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => {
setUser(data);
setIsLoading(false);
})
.catch((err) => {
if (err.name === 'AbortError') return;
setError(err);
setIsLoading(false);
});
return () => controller.abort();
}, [userId]);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{user.name}</h1>;
}In development with Strict Mode, the sequence is:
- Setup sends request A.
- Cleanup aborts request A. The
catchhandler sees anAbortErrorand returns without touching state. - Setup sends request B. Its response is the one that updates state.
In the Network tab you will see two requests to the same URL, and the first is marked as canceled. The user sees the right result and never sees A's data. This is the effect working as designed.
If you skipped cleanup, both requests would complete and both would call setUser. For identical data this looks harmless, but with a changing userId it produces the stale-response race from the earlier chapter. Strict Mode's second run is a cheap rehearsal of that race.
The ignore flag alternative
Aborting is not the only correct cleanup. You can let the request finish and ignore its result:
useEffect(() => {
let ignore = false;
fetch(`/api/users/${userId}`)
.then((response) => response.json())
.then((data) => {
if (!ignore) setUser(data);
});
return () => {
ignore = true;
};
}, [userId]);This is correct for state, but it does not cancel network work, so both requests still reach the server. Prefer AbortController when the request is expensive or the response is large.
Fixes that do not work
Two common reactions make the symptom disappear while leaving the underlying problem in place.
- Removing
<StrictMode>. The double request goes away, but so does the warning system. Cleanup bugs will then appear in production instead. - Guarding with a ref. Code such as
if (hasFetched.current) return;skips the second setup. This breaks when the user navigates away and back, because the component remounts with fresh state but the guard logic may not match, and it hides the missing cleanup. It also skips the second run only in development, so you are testing different behavior than you ship.
Side effects that should not be in an effect
Some actions cannot be undone by cleanup. Sending a payment, creating a record with POST, or sending an email is not "setup" for something visible on screen. If a component would do this twice in Strict Mode, the real problem is that the action is triggered by rendering rather than by the user.
Move these actions into event handlers, such as a button's onClick, or into a mutation. An effect should synchronize the component with something external, such as loading data, a subscription, or a timer. It should not be the place where a user's intent is carried out.
One case needs judgment: analytics events such as "page viewed." Logging in an effect will log twice in development. That is acceptable if the duplicate is only in development, and many teams simply tolerate it. If you must avoid duplicates, deduplicate in the analytics layer rather than blocking the second effect run.
Quick reference
| Symptom in development | Likely cause | Fix |
|---|---|---|
| Two identical requests, the first canceled | Normal Strict Mode cycle with abort cleanup | Nothing to fix |
| Two identical requests, both complete | Effect has no cleanup | Add `AbortController` or an ignore flag |
| Timer or listener fires twice as often | Subscription is not removed | Return a cleanup that removes it |
| Duplicate record created on the server | Write triggered from an effect | Move it into an event handler or mutation |
| Console logs appear twice from the component body | Render double-invocation | Keep render pure, ignore the logs |
Checking that production is fine
Strict Mode only runs in development, so it is worth confirming that your fix is not accidental. Build the app and run the production output. If the app works with a single run and with the double run, your effects are symmetrical. If you want to test the remount case directly, temporarily render the component conditionally behind a toggle button and switch it off and on. A correct effect behaves the same each time.
Exercise
Your useEffect opens a WebSocket in setup and has no cleanup. In development you notice two connections open on page load. A teammate suggests wrapping the setup in if (!hasConnected.current). Why is this the wrong fix, and what should you do instead?
Show answer
The second connection exposes a missing cleanup. It would also leak in production if the component unmounted and remounted, for example when the user navigates away and back. A ref guard hides the problem in development without removing it. Return a cleanup function from the effect that closes the socket, such as return () => socket.close();. The simulated unmount then closes the first connection, and the second setup opens a fresh one.
Exercise
A component sends fetch('/api/orders', { method: 'POST', body }) inside useEffect on mount, and each page load in development creates two orders. Cleanup with AbortController does not prevent it. Why, and where should the request go?
Show answer
Aborting cancels the browser's wait for the response, but the server may already have received and processed the request. A POST that creates data is not safe to repeat, and it should not be triggered by rendering at all. Move it into an event handler, such as the click handler of a "Place order" button, or into a mutation, so it only runs when the user acts.