The useEffect Dependency Array: Every Rule and Why It Exists

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 1

Advanced Dependency Array

Three tricky dependency array scenarios — function deps, values defined inside the effect, and why functional updaters let you drop state from deps.

1
function Component({ userId, onLoad }) {
  useEffect(() => {
    fetchUser(userId).then(onLoad);
  }, [userId]); // eslint warns: onLoad missing
}

The linter says onLoad is missing from deps. Is it actually needed?

2
function SearchBox() {
  const [query, setQuery] = useState('');

  useEffect(() => {
    const options = { method: 'GET', headers: {} };
    fetch('/api/search?q=' + query, options);
  }, [query, options]); // options is declared inside the effect
}

What is wrong with this dep array?

3
const [data, setData] = useState([]);

useEffect(() => {
  setData(prev => [...prev, newItem]);
}, [newItem, data]); // data in deps

Is "data" needed in the dep array here?

0/3 answered

💡 The rule: include every reactive value the effect closes over. Exceptions: values defined inside the effect (not reactive), and functional updaters that receive state as an argument (don't close over it).

Practice: The useEffect Dependency Array: Every Rule and Why It Exists — Interactive Exercises | Durgesh Rai