Why twice. React may unmount and remount a component without the user noticing: navigating away and back, <Activity> hiding a tree and showing it again, saving the file in development. An effect that sets something up but never tears it down leaks a connection, a listener or a timer each time. To surface that early, Strict Mode in development runs every effect's setup → cleanup → setup when a component first mounts. State is kept, so only the effects (and, since React 19, ref callbacks) repeat. Production builds run setup once.
The right question isn't "how do I run it once?" but "does my effect survive a remount?" The test is that a user can't tell one setup from setup → cleanup → setup.
What cleanup does. Return a function that stops or undoes the setup: disconnect, remove the listener, clear the interval, destroy the widget, ignore or abort the request. React calls it:
- before running the effect again because a dependency changed. It's the closure from the previous render, so it sees the previous values;
- once when the component unmounts.
Within one commit, React runs every pending cleanup in the tree before any new setup.
Data fetching races. When query changes from r to re, two requests are in flight and the older one may answer last. Without cleanup, its setResults overwrites the newer result. Set an ignore flag in cleanup, or abort the request with an AbortController, so only the latest effect's response is applied. (Libraries and frameworks handle this, plus caching, for you.)
Don't use a ref to skip the second run. It hides the missing cleanup in development, and the leak still happens on real remounts. Work that must happen once per page load, not per mount, belongs outside components, at module level.