A shop's dashboard shows a toast for every new order. In development, each order popped up twice, so a developer traced it to the Effect running twice and added a useRef flag to subscribe only once. One toast per order, ticket closed. A week after release, store managers reported the doubles were back: open Settings, return to the dashboard, and every order pops up twice; go round again and it's three times. Managers who switched to another branch saw the opposite: no alerts for the new branch, while the old branch's orders kept arriving. Strict Mode had shown the bug on day one, and the ref had hidden it.
The common misconception
The belief: an Effect that runs twice when the component mounts, in development only, is React misfiring. Production runs it once, so the fix is to delete <StrictMode> from the entry file, or guard the Effect with a has-run ref so the second call returns early.
It's an easy conclusion to reach. The double run never happens in production, so it looks like noise that doesn't reflect what users get. The log shows two identical calls with nothing changing in between. And the ref works, in the sense that the log goes back to one line. An earlier article in this path showed why an Effect is synchronization, not "code that runs on mount". This one is about what the second run tests, and why both popular fixes fail.
What actually happens
Four checks, all in development
React's docs list what turns on: an extra render of every component, to catch impure rendering; one extra setup and cleanup cycle for every Effect, to catch missing cleanup; the same extra cycle for every ref callback; and warnings for deprecated APIs. All of them apply to everything inside <StrictMode>, however deep, and none of them affect the production build.
For an Effect, mounting in development becomes setup → cleanup → setup. React remounts the component once to see whether your really undoes your setup. The docs give the rule for passing: the user shouldn't be able to tell that sequence apart from a single setup, which is what production runs.
It rehearses remounts production does too
A remount isn't a development quirk. Every time a user leaves a screen and comes back, its components mount again and their Effects run again. React's <Activity> component goes further: when it hides its children, it keeps their state but destroys their Effects, and when it shows them again, it restores the state and re-creates the Effects. That's a cleanup followed by a setup, with state kept, which is the very sequence Strict Mode simulates. The Activity docs say to think of hidden content as unmounted, and recommend Strict Mode to find problematic Effects early.
Why a has-run ref hides the bug
TSX · NewOrderAlerts.tsx
import { useEffect, useRef } from "react";export function NewOrderAlerts({ storeId }: { storeId: string }) { const subscribed = useRef(false); useEffect(() => { if (subscribed.current) return; // hides the second run subscribed.current = true; subscribeToOrders(storeId, (order) => { showToast(`New order #${order.id}`); }); }, [storeId]); return null;}
During the rehearsal, React keeps the component's refs, so the guarded version skips its second setup and you see one subscription. That's the only remount the guard handles. Leaving the dashboard unmounts the component without unsubscribing, and coming back creates a new component with a fresh ref that subscribes again: two live subscriptions, two toasts per order. When storeId changes, the guard returns early, so the new branch never gets a subscription while the old one keeps firing.
The fixed version needs no flag. In development it subscribes, unsubscribes and subscribes again, which leaves exactly one subscription, as in production. Changing branch or leaving the page runs the same cleanup, so every path ends with one subscription for the current store. React's docs put the question this way: not how to run an Effect once, but how to make it work after remounting.
Not every double is a bug
The test is what the user sees, not how many times a line ran. A second fetch in the Network tab is fine when the cleanup aborts or ignores the first, as the article on fetching in Effects showed. A duplicate analytics event is fine too: the docs recommend keeping that code as it is, because production sends one and development events shouldn't reach production metrics anyway. Calling something twice with the same value, like setting a map's zoom level, needs no cleanup at all.
But when remounting breaks the logic, the code is usually in the wrong place. A purchase sent from an Effect would repeat whenever the user comes back to the page, so it belongs in the click handler. Setup that must happen once per page load, like checking an auth token, belongs at module level, outside any component.
What you see twice
What it means
What to do
Two subscriptions or connections
Setup has no matching cleanup
Return unsubscribe or disconnect
An item registered twice by a ref callback
The ref callback has no cleanup
Return a cleanup that unregisters it
Two requests in the Network tab
Fine if the first result is dropped
Abort or ignore it in cleanup
Two analytics events
Expected in development only
Keep the code; production sends one
Two purchase requests
The request isn't caused by rendering
Move it to the click handler
In React 19, a ref callback can return a cleanup function, which React calls when the node is detached. Strict Mode runs that pair an extra time too, so a ref that registers a node somewhere, like a marker on a map, should unregister it in the cleanup it returns.
How to apply it in your project
Keep StrictMode at the rootRender <StrictMode><App /></StrictMode> in the entry file, and treat every double you notice as a question about cleanup.
Hunt down has-run refsSearch for useRef(false) and early returns at the top of Effects. Replace each guard with a cleanup that undoes the setup, then check that the Effect still follows its dependencies.
Pair every setup with its undoSubscribe and unsubscribe, connect and disconnect, register and unregister, in Effects and in ref callbacks alike.
Move what isn't synchronizationRequests caused by a click go to its handler; work that runs once per page load goes to module level.
Key takeaways
In development, Strict Mode runs each Effect's setup, cleanup and setup again on mount; production runs setup once.
The rehearsal mirrors real remounts: leaving and returning to a screen, or an Activity being hidden and shown.
A has-run ref survives only the rehearsal; real remounts and dependency changes still break the Effect.
Judge doubles by what users see: extra fetches and dev analytics are fine, duplicate subscriptions and purchases are bugs.
التعليقات (0)