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, React runs the old cleanup and then the effect again with the new values.
An empty list means there is nothing to watch, so the effect runs only after the first render. No list at all means run after every single render, which is rarely what you want for anything beyond quick logging.
The list is not a free choice. It must contain every reactive value the effect reads: props, state, and any variable or function created inside the component. Leaving one out means the effect keeps using an old copy of that value.
Example
useEffect(() => { document.title = "Home"; }); // every render
useEffect(() => { connect(); return disconnect; }, []); // mount and unmount
useEffect(() => { fetchScore(matchId); }, [matchId]); // when matchId changesWhat 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.