Sub topic 7
Why effects run twice in development
This chapter assumes you know useEffect and its dependency array, the fetch API with AbortController, and how to write cleanup functions. You have probably seen a request fire twice in the Network tab while developing. This chapter explains why and what to do about it.
What Strict Mode does
<StrictMode> is a React component that adds extra checks in development. In React 18 and later, it mounts each component, runs its effects, runs their cleanups, and then runs the effects again. The sequence is:
- Mount: effect runs.
- Simulated unmount: cleanup runs.
- Simulated remount: effect runs again.
This happens only in development builds. A production build runs each effect once.
Why React does this
A component can be unmounted and mounted again with its state preserved. Features such as Offscreen rendering can hide a screen and restore it later. React's rule is that an effect must be able to start, stop, and start again without leaving anything behind.
Running the cycle on every mount in development exposes effects that lack a correct cleanup. If your effect opens a connection, subscribes to an event, or starts a request, the cleanup must undo it. If it does not, you see the problem immediately instead of in a rare production case.
What you see with fetching
Consider an effect with an abort cleanup:
import { useEffect, useState } from 'react';
function UserName({ userId }) {
const [name, setName] = useState(null);
useEffect(() => {
const controller = new AbortController();
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) => setName(data.name))
.catch((error) => {
if (error.name === 'AbortError') return;
console.error(error);
});
return () => controller.abort();
}, [userId]);
return <p>{name ?? 'Loading...'}</p>;
}In development, the Network tab shows two requests to /api/users/1. The first is cancelled and shows as aborted. The second completes and updates state. The screen shows the correct result, which means the cleanup works.
Without controller.abort(), both requests would finish and both would call setName. The responses could arrive out of order, which is the race condition from an earlier chapter. Strict Mode makes that bug visible during development.
What not to do
It is tempting to silence the second request. Two common attempts are wrong:
- Removing
<StrictMode>. This hides the problem and does not fix it. The same bug can appear in production when a component remounts or whenuserIdchanges quickly. - Using a
useRefflag such ashasFetchedto skip the second run. This breaks the cleanup contract and can leave stale data when the inputs change.
When the double run is a real signal
Some effects must not run twice, such as sending an analytics event or a purchase request. Ask whether the action belongs in an effect at all.
- If it happens because the user did something, put it in an event handler. Handlers do not run twice.
- If it happens because the component appeared on screen, such as logging a page view, you can often accept a duplicate in development. The production build sends one event.
- If duplicates matter in production, the server needs to deduplicate, for example with an idempotency key.
Data fetching with a GET request is safe to repeat, so the double run costs only an extra request in development. The next chapters build on this when they extract a reusable hook and then replace effects with a query library that deduplicates requests for you.
Exercise
In development, your component's effect starts a fetch with an AbortController and returns a cleanup that calls abort(). The Network tab shows two requests, and the first is marked cancelled. Is this a bug? What would you check if both requests completed and the page flickered between two values?
Show answer
It is not a bug. Strict Mode runs setup, cleanup, and setup again, and the abort cancels the first request. If both requests complete and the page flickers, the cleanup is missing or does not abort the request, so check that the effect returns a function that calls controller.abort() and that the fetch receives controller.signal.