React's useEffect: The Sync Mechanism, the StrictMode Double-Run, and Why Infinite Loops Happen
A wrong mental model of useEffect produces infinite loops, memory leaks, and stale data in production. The double-invoke in StrictMode is a deliberate bug detector, not something to work around; treating effects as synchronization rather than lifecycle callbacks removes most of these failures.
React's useEffect synchronizes component state with the outside world. It runs after the browser paints, and its cleanup function runs before the next effect or on unmount. The mental model that matters: think of it as declaring which state and props an effect depends on, not as a lifecycle replacement.
The dependency array decides when effects fire. No array means every render; an empty array means once on mount; a populated array runs when any listed value changes. StrictMode in development runs mount effects twice (run, cleanup, run) to expose improper cleanup; production builds run once, so there is nothing to fix beyond writing idempotent effects and clean cleanup.
Common failures come from reference equality: objects, arrays, and functions get new identities each render, so putting them in dependencies causes infinite loops without useMemo or useCallback. Stale closures, missing dependencies, and heavy synchronous work are the other traps. The practical fixes are one effect per concern, complete dependency arrays, race condition handling with a cancelled flag or AbortController, and extracting reusable logic into custom hooks.
The dependency array is only as reliable as the identity of its values; object and function literals break it every render, which is why StrictMode's remount is so effective at exposing bad assumptions.
StrictMode's intentional double-run is a test harness for cleanup logic, not a production behavior. Code that survives it runs with confidence in production, though newcomers often waste time trying to suppress it.
Splitting effects by responsibility turns the dependency array into a declaration of granular needs, making the synchronization model explicit and cutting down on the cognitive load of tracking which state an effect reads.
The fact that effects run twice under StrictMode really confuses novices the first time they encounter it; pointing it out in advance is necessary. The dependency array and cleanup function are two pitfalls that you won't forget after stepping on them once.