More React answers

by Danny
Published 2 min read

In development, React Strict Mode mounts components twice to expose effects without cleanup. Learn why it happens, why production is unaffected, and how to write effects that cope.

The short answer

#

React Strict Mode deliberately mounts each component, unmounts it, and mounts it again in development. Your effect runs, its cleanup runs, then the effect runs again. This only happens in development. The fix is not to stop it, but to give the effect a cleanup function so running it twice does no harm.


_10
useEffect(() => {
_10
const connection = createConnection(roomId);
_10
connection.connect();
_10
_10
return () => {
_10
connection.disconnect(); // undo whatever the effect did
_10
};
_10
}, [roomId]);

Why it happens

#

Effects are meant to sync your component with something outside React: a subscription, a timer, a socket, a third-party widget. In a real app, components mount and unmount many times. Users navigate away and back, React may hide and restore parts of the tree with features like Activity, and fast refresh remounts components while you edit.

If an effect sets something up but never tears it down, those remounts leave duplicates behind: two event listeners, two intervals, two open sockets. Strict Mode surfaces this early by running one extra setup and cleanup cycle straight after the first mount. If your component behaves the same after that cycle, your effect is safe.

Strict Mode is switched on with the StrictMode component. Next.js enables it by default for the App Router, and most new project templates wrap the app in it too. React 19 still does the double mount in development, and production builds never do.

How to fix it

#

Add a cleanup that mirrors the setup

Every add needs a remove, every subscribe an unsubscribe, every setInterval a clearInterval.


_10
useEffect(() => {
_10
function handleResize() {
_10
setWidth(window.innerWidth);
_10
}
_10
window.addEventListener('resize', handleResize);
_10
return () => window.removeEventListener('resize', handleResize);
_10
}, []);

Ignore stale results when fetching

Fetching in an effect will send two requests in development. That is fine as long as the first result cannot overwrite the second. Use an ignore flag or an AbortController.


_12
useEffect(() => {
_12
const controller = new AbortController();
_12
_12
fetch(`/api/users/${userId}`, { signal: controller.signal })
_12
.then((res) => res.json())
_12
.then(setUser)
_12
.catch((error) => {
_12
if (error.name !== 'AbortError') throw error;
_12
});
_12
_12
return () => controller.abort();
_12
}, [userId]);

In a framework such as Next.js, prefer fetching on the server or with a data library that caches and de-duplicates requests, so you do not need an effect at all.

Move one-off actions out of effects

Some code should only ever run once per user action, such as sending a purchase or logging an analytics event for a click. Put that code in the event handler that triggers it, not in an effect.


_10
function BuyButton({ productId }: { productId: string }) {
_10
async function handleClick() {
_10
await fetch('/api/buy', { method: 'POST', body: JSON.stringify({ productId }) });
_10
}
_10
return <button onClick={handleClick}>Buy</button>;
_10
}

For code that should run once when the app starts, such as initialising an SDK, run it at module level outside any component, or guard it with a module-level variable.

Common pitfalls

#
  • Removing StrictMode to make the double run go away. The bug it found is still there and will appear in production when components remount.
  • Using a ref flag such as hasRun.current to skip the second run. It hides the problem and breaks when React genuinely remounts the component.
  • Assuming production also runs effects twice. It does not; if you see duplicates there, look for a missing cleanup or a component that mounts twice.
  • Forgetting that the render function also runs twice in Strict Mode. Keep rendering pure and free of side effects.
#

Was this resource helpful?