Sub topic 12
Why effects run twice in development
This chapter assumes you know useState, the render and commit cycle, and how useEffect cleanup works. It explains why an effect's setup code seems to run twice, and how to write effects that don't mind.
What Strict Mode does
<StrictMode> is a wrapper component that adds extra checks in development. In React 18 and later, it does two things:
- It renders each component twice, to expose impure rendering.
- It mounts each component, unmounts it, and mounts it again. As a result, every effect runs setup, then cleanup, then setup.
Production builds skip both checks. Your users never see the double run.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);The reason for the extra cycle
An effect should synchronize a component with something outside React. It should be able to start, stop, and start again at any time. React may unmount and remount a component in real use, for example when a user navigates away and back, or when features that preserve state are used. The development-only cycle simulates this on every mount. If your cleanup is missing or wrong, the problem shows up on your machine instead of in production.
Seeing the cycle
This component logs each step of a connection.
import { useEffect } from 'react';
function Room({ roomId }) {
useEffect(() => {
console.log(`Connect to ${roomId}`);
return () => console.log(`Disconnect from ${roomId}`);
}, [roomId]);
return <h1>Room: {roomId}</h1>;
}In development, the console shows "Connect", "Disconnect", "Connect". The final state is one open connection, which is correct. Because cleanup undoes setup, the extra cycle does no harm.
What a bug looks like
An effect without cleanup leaves a duplicate behind.
import { useEffect, useState } from 'react';
function Width() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
// Missing: return () => window.removeEventListener('resize', onResize);
}, []);
return <p>{width}px</p>;
}Strict Mode adds two listeners, and one is never removed. Adding the commented-out cleanup fixes it.
What to do for common cases
| Effect | Cleanup that makes it safe |
|---|---|
| Event listener | `removeEventListener` |
| Timer | `clearInterval` or `clearTimeout` |
| Fetch | `controller.abort()` and ignore `AbortError` |
| Subscription or socket | `unsubscribe()` or `close()` |
Some work should not be repeated, such as sending an analytics event for a purchase. That work belongs in an event handler. If it is a page-view event, it is acceptable for it to fire twice in development, since production fires it once.
Common mistakes
- Treating the second run as a React bug. It is deliberate.
- Expecting the double run in production. It does not happen there.
- Seeing duplicate network requests in development and "fixing" them. An aborted first request is the intended result.
Exercise
A component's effect adds a setInterval and has no cleanup. In development under Strict Mode, the counter ticks twice per second. Why, and how do you fix it?
Show answer
Strict Mode runs setup, cleanup, setup. With no cleanup, the first interval is never cleared, so two intervals run. Fix it by saving the id and returning () => clearInterval(id) from the effect.