Course contentsShow
← React
Lesson 614 of 2,39617. Common useEffect MistakesFree lesson

Why Missing Dependencies Break Your Effects

Effects capture stale values from their first render when dependencies are omitted, causing bugs.

Why Missing Dependencies Break Your Effects

What you'll learn: How omitting dependencies from your useEffect array causes your effect to capture stale values, leading to subtle but serious bugs.

The Stale Closure Problem

When you leave a dependency out of your useEffect array, React doesn't re-run your effect when that value changes. This means your effect keeps using the old value from the first render—a problem called a "stale closure."

Think of it like taking a photograph: your effect captures the values that existed at the moment it was created. If those values change outside the photo, your effect doesn't see the updates—it's still looking at the old snapshot.

A Simple Example

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      console.log(`Count is: ${count}`);
    }, 1000);

    return () => clearInterval(timer);
  }, []); // ❌ Missing 'count' dependency!

  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

What happens? The console always logs "Count is: 0" even as you click the button. The setInterval callback captured count from the first render (when it was 0) and never updates.

Why This Happens

Effects with empty dependency arrays [] only run once on mount. The effect's closure "freezes" the values from that first render. When count changes, React re-renders the component with the new value, but your effect isn't re-run—it's still using the old count from its original snapshot.

Key Takeaway: Every value from your component scope that your effect uses must be in the dependency array, or your effect will use stale values and behave incorrectly. The exhaustive-deps ESLint rule exists specifically to catch this common mistake.