MyInternships.in

React Hooks

React useEffect Dependency Array

The dependency array tells React which reactive values the effect reads. React compares each entry with the previous render using Object.is and re-runs the effect only when one has changed.


What is useEffect Dependency Array in React?

The dependency array tells React which reactive values the effect reads. React compares each entry with the previous render using Object.is and re-runs the effect only when one has changed.

Why useEffect Dependency Array matters

Almost every useEffect bug is a dependency bug: missing entries cause stale values, unstable entries cause endless loops. Learning to read the array is learning to debug effects.

useEffect Dependency Array example

Unstable dependencies and the fixes
JSX
// ❌ options is a NEW object every render -> effect runs forever
const options = { city, role };
useEffect(() => { search(options); }, [options]);

// ✅ depend on the primitives instead
useEffect(() => { search({ city, role }); }, [city, role]);

// ✅ or memoise the object
const options = useMemo(() => ({ city, role }), [city, role]);
useEffect(() => { search(options); }, [options]);

How this works

Object.is compares references for objects, and a fresh literal is never equal to the previous one. Depending on primitives, or memoising the object, gives React something stable to compare.

Key points to remember

  • Include every reactive value the effect reads: props, state, context, and functions defined in the component.
  • Refs and state setters are stable — they never need to be listed.
  • Prefer removing a dependency by restructuring over silencing the lint rule.
  • Functions declared inside the component change identity each render; wrap them in useCallback or move them inside the effect.

Common mistakes with useEffect Dependency Array

  • Adding // eslint-disable-next-line react-hooks/exhaustive-deps to hide a real staleness bug.
  • Listing a function prop without asking the parent to stabilise it.
  • Passing an empty array when the effect actually reads changing props.

React useEffect Dependency Array— Interview Questions & FAQs

Should I always follow the exhaustive-deps lint rule?+

Yes, treat it as correct and change the code rather than the array. If a dependency causes loops, make it stable with useCallback or useMemo, move the function inside the effect, or use a functional state update.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships