The dependency array tells React which values the effect reads. When any dependency changes, React re-runs the effect after the next render.
Rules of thumb
- Include every prop and state variable used inside the effect
- Stable setters from
useStatedo not need to be listed (React guarantees stability) - Objects and arrays as dependencies compare by reference—memoize or depend on primitives
Stale closures
Missing dependencies can show outdated values—the effect “closes over” old state. ESLint’s react-hooks/exhaustive-deps rule catches most mistakes in real projects.
Important interview questions and answers
- Q: Empty deps vs no deps?
A:[]runs once per mount; omitting the array runs after every render. - Q: Infinite loop symptom?
A: Effect sets state that is in its dependency array without a guard—fix logic or split effects.
Self-check
- Why does changing
userIdrequire listing it in deps? - What happens if you pass a new object literal in deps every render?
Tip: ESLint react-hooks/exhaustive-deps warns about stale closures—fix deps or refactor, do not silence blindly.