React useEffect runs twice / API called twice in development
#146Error
useEffect fires twice on mount, fetch or analytics event runs two times, console.log prints twice (only in development)
Why it happens, and why this works
In development, React 18+ StrictMode mounts, unmounts and remounts every component once to expose effects that are missing cleanup. With a proper cleanup the first run is cancelled, so only one result is used.
Fix
This is React StrictMode testing your effect; make the effect safe to run twice, don't remove StrictMode.
1. Return a cleanup that undoes the effect: for fetch use an AbortController (const c = new AbortController(); fetch(url, { signal: c.signal }); return () => c.abort()), or an ignore flag (let ignore = false; ...; if (!ignore) setData(d); return () => { ignore = true }).
2. Subscriptions/timers/sockets: unsubscribe/clearInterval/close in the cleanup.
3. One-time side effects that must not repeat (charging, sending an email, POST that creates a row) belong in an event handler, not an effect.
4. Production builds run effects once; check there before 'fixing' a double request.Did it work?
No reports yetKnown good on: react@18
Related fixes
Invalid hook call. Hooks can only be called inside of the body of a function component
#151Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app
RuntimeError: asyncio.run() cannot be called from a running event loop
#160RuntimeError: asyncio.run() cannot be called from a running event loop
fetch('/api/...') on the server: Failed to parse URL
#34TypeError: Failed to parse URL from /api/users (Invalid URL) when calling fetch in Node, SSR or a server component