What does the dependency array do in useEffect?
It tells React when to re-run the effect. No array means after every render, an empty array means once after mount, and a list of values means after renders where one of them changed, compared with Object.is.
Explain it simply
The dependency array is a watch-list. After each render React checks every item on it. If nothing changed since the last run, the effect is skipped. If anything changed, the effect cleans up and runs again.
An empty list means nothing to watch, so the effect runs only after the first render. No list at all means run after every render.
Example
useEffect(() => { document.title = "Home"; }); // every render
useEffect(() => { connect(); return disconnect; }, []); // mount and unmount
useEffect(() => { fetchScore(matchId); }, [matchId]); // when matchId changesList every reactive value used inside the effect: props, state and functions defined in the component.
What to say in the interview
"The array controls when the effect re-runs: omitted means every render, empty means once on mount, and values mean whenever any of them changes. Everything reactive used inside the effect belongs in the array. I trust the exhaustive-deps lint rule instead of hiding dependencies."
Common mistakes
- Leaving a dependency out to stop re-runs, which causes stale closures.
- Using an empty array on an effect that reads props.