Skip to content

Why does my useEffect run twice in Strict Mode?

IntermediateAsked very oftenCoding roundDebuggingReact
Asked atMetaVercelShopify
#react#useeffect#strict-mode#cleanup

Company tags are compiled from public interview reports and are signals, not guarantees.

What interviewers are testing

Interviewers want to see whether you understand why React 18 StrictMode double-invokes effects — mount, simulated unmount, remount — and whether you reach for the correct fix. The tell is whether a candidate disables StrictMode to silence a symptom or writes an effect that survives being set up and torn down twice.

Mental model

In development, StrictMode deliberately mounts, cleans up, and remounts every component to prove your effects are resilient. Effects must be idempotent: setup and cleanup should be able to run in any order and any number of times. Production invokes the effect exactly once, so code that only works because it never cleaned up is a latent bug.

Step-by-step solution

  1. Step 1: The duplicated network calls

    Open a fresh React 18 app, put a fetch or a subscription inside useEffect, and the network tab shows the work twice — while the production build shows it once. Candidates usually blame the fetch, the cache, or the dev server. The real trigger is StrictMode, which React enables in development templates. Watch the first animation: React renders the component twice before any effect runs, then the console prints subscribe, unsubscribe, subscribe in a tight rhythm and goes quiet. That rhythm is the fingerprint of an intentional effect setup, cleanup, and setup cycle. The important question is not how to silence the duplicate log — it is why React insists your effect survive a teardown it never asked you to write. If the effect is correct, the double invoke is harmless; if it is not, StrictMode has just exposed a bug that a real unmount or dependency change would eventually trigger in production.

  2. Step 2: StrictMode is a debugger

    StrictMode is not a linter or a scaffold you should strip out; it is a deliberate correctness harness. StrictMode double-invokes render logic in development — component bodies, initializers passed to useState and useMemo, and state updater functions — so that non-idempotent code fails loudly on your machine instead of silently in production. React 18 added the effect half of that simulation: in development each effect runs setup, cleanup, then setup again, to prepare apps for concurrent rendering, where a component can be mounted, paused, and discarded before it ever commits. The animation walks the full dev lifecycle — render, render, setup, cleanup, setup — before the user ever sees a symptom. Any effect that connects, subscribes, or starts a timer must return a cleanup that fully reverses its setup. When the cleanup is complete, the remount becomes invisible: same final state, one live connection, no leaked listener. The double invoke is the test; the cleanup is the answer.

  3. Step 3: Trace the lifecycle counters

    Now trace the counters. renderCount tracks how many times the component body runs, effectRuns counts setup functions, and cleanupRuns counts teardowns. In development StrictMode renders the body twice before any effect runs; then setup runs, StrictMode immediately invokes the returned cleanup — cleanupRuns becomes one only after that second render — and setup runs a second time, so effectRuns reaches two while only the second subscription stays live. Watch the final frame: production does not run this simulation, so you see one render, one setup, and zero cleanups until the component actually unmounts. The counters make the rule concrete — whenever setup runs, cleanup must be able to run too, in any order, without leaving duplicate subscriptions, timers, or listeners behind. If your cleanup is complete, the counters are boring in production and healthy in development.

    tsx
    function ChatRoom({ roomId }: { roomId: string }) {
      const [messages, setMessages] = useState<string[]>([]);
    
      useEffect(() => {
        console.log('setup', roomId);
        const sub = chat.subscribe(roomId, setMessages);
        return () => {
          console.log('cleanup', roomId);
          sub.unsubscribe();
        };
      }, [roomId]);
    
      return <ul>{messages.map((m) => <li key={m}>{m}</li>)}</ul>;
    }
  4. Step 4: Production still needs cleanup

    Production never double-invokes on mount, so where do cleanups come from? Dependency changes and unmounts. The animation follows roomId switching from general to random: React first runs the previous effect's cleanup to leave the general room, then runs the new setup to join random. Only one subscription is ever live. Leave the screen and the final cleanup runs on unmount. This is the deeper lesson of the StrictMode question: the dev-mode simulation is just an accelerated version of lifecycle events that happen all the time in production. Every dependency change is a mini remount, and every navigation away is a cleanup. An effect that only cleans up correctly when it is convenient will leak subscriptions, stale timers, and out-of-order responses. Writing effects that tolerate arbitrary setup and cleanup ordering is the same skill as handling routes correctly.

  5. Step 5: Make effects idempotent

    The fix is to make setup and cleanup exact mirrors. Keep every resource — subscription, interval, AbortController, WebSocket — inside the effect closure and release it in the returned function. For fetches, pass an AbortController signal and abort in cleanup so a stale response cannot call setState; the abort rejects with AbortError, which you ignore. For timers, clear the interval. For analytics, decide explicitly which events must fire once and guard them outside the effect. Never disable StrictMode and never "fix" the duplicate with a mountedRef guard: refs survive the simulated remount, so the guard can skip the second setup after the first was cleaned up, leaving zero live subscriptions. Watch the animation: two setups run, but only the second fetch wins, and the first is aborted cleanly. Idempotent effects are the real production requirement.

    tsx
    useEffect(() => {
      const controller = new AbortController();
    
      fetch('/api/rooms/' + roomId, { signal: controller.signal })
        .then((res) => res.json())
        .then(setRoom)
        .catch((err) => {
          if (err.name !== 'AbortError') setError(err);
        });
    
      return () => controller.abort();
    }, [roomId]);

Edge cases & traps

  • State from the first run clobbers the second: abort the stale request (AbortController) or ignore it with a canceled flag in cleanup.
  • Not resetting refs, intervals, or third-party widgets in cleanup: return a teardown that reverses every side effect the setup started.
  • Removing StrictMode to hide the duplicate: the missing cleanup is still a bug and will fire on route changes and dependency changes in production.
  • Guarding setup with a mountedRef: refs survive the simulated remount, so the second setup is skipped after the first was cleaned up — leaving zero live subscriptions.
  • Double-counting analytics events in development: decide deliberately which events must fire once and dedupe them outside the effect rather than disabling the check.

Follow-up questions

Go deeper: Explore the React Cosmos visualizer