The dependency array lists every reactive value the effect reads: props, state, and anything declared in the component body, functions included. It isn't a "when to run" switch; it describes the code.
- No array: the effect runs after every commit.
[]: it reads nothing reactive, so it runs after mount only.[a, b]: React compares each item with the previous render's usingObject.isand re-runs the effect if any differs. Objects and functions created during render are new every time, so they always differ.
Stale closures. Every render calls your component again, creating a new effect function that closes over that render's values. When dependencies are unchanged, React doesn't run the new effect; whatever the old one set up keeps running with the values it saw. Omit count from an interval effect and the interval keeps reading count from the first render forever.
The react-hooks/exhaustive-deps lint rule catches this and suggests a fix. Don't silence it; change the code so it no longer needs the value:
- The effect should re-sync when the value changes: list it. That's the usual answer.
- The value is only used to compute the next state: use an updater,
setCount(c => c + 1). The effect no longer readscount. - An object or function made during render: create it inside the effect, depend on its primitive parts, or move static ones out of the component.
useMemo/useCallbackwork but move the problem to their own dependencies. - The effect needs the latest value without re-syncing on it (a theme in a "connected" notification): read it in an Effect Event,
useEffectEvent.
useRef objects and useState setters have stable identities, so they can be omitted; the linter knows that when it can see where they come from.