In development with <StrictMode> (React 18+), React mounts each component, immediately simulates an unmount (running effect cleanups), and mounts it again (running setups again). That's why useEffect(() => {...}, []) appears to run twice. It's deliberate: it verifies that every effect's cleanup correctly undoes its setup, so components stay correct when React unmounts and remounts them (Fast Refresh, <Activity>, back/forward navigation, future features). Production runs effects once. The fix is almost never "prevent the second run". Write the cleanup, so setup → cleanup → setup behaves like a single setup.
useEffect(() => {
console.log('connect');
const conn = createConnection(roomId);
conn.connect();
return () => {
console.log('disconnect');
conn.disconnect();
};
}, [roomId]);
// Development: connect, disconnect, connect
// Production: connect
Without the cleanup, development shows two live connections, exposing a leak that would also appear in production whenever roomId changes or the component remounts.
Subscriptions and listeners: remove them in the cleanup.
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
Data fetching: ignore or abort the stale request.
useEffect(() => {
const controller = new AbortController();
fetch(`/api/items?q=${q}`, { signal: controller.signal })
.then(r => r.json())
.then(setItems)
.catch(e => { if (e.name !== 'AbortError') setError(e); });
return () => controller.abort();
}, [q]);
Development still sends two requests (the first is aborted). That's fine. Better still, use a data library or framework loader that caches and deduplicates.
Third-party widgets: destroy the instance in the cleanup (map.remove(), chart.destroy()).
Animations: reset to the initial state in the cleanup.
Analytics "page view": the dev double-fire is harmless. If it pollutes dev data, disable analytics in development rather than distorting the code.
didInit flag, not in an effect with [].// Hiding the symptom
const ran = useRef(false);
useEffect(() => {
if (ran.current) return;
ran.current = true;
subscribe(); // never unsubscribed, still a leak
}, []);
Also avoid removing <StrictMode> to "fix" it. You lose the check, and the bug remains for real remounts.
useMemo/useCallback reuse results from the first render during the double render.Spotted a mistake or a rights concern? Report an issue