Course contentsShow
← React
Lesson 544 of 2,39615. useEffect FundamentalsFree lesson

Why Missing Dependencies Cause Bugs

Understand stale closures: when your effect captures old values because you didn't list all dependencies.

Why Missing Dependencies Cause Bugs

What you'll learn: How forgetting to list dependencies in your useEffect creates stale closures that capture old values and cause subtle bugs.

When your effect function runs, it "captures" the values of props and state at that moment—like taking a snapshot. If you forget to list a dependency, your effect keeps using that old snapshot even after the values change.

The Stale Closure Problem

Imagine you write a note to yourself: "Call the number on my desk." Later, the number changes, but you still have the old note. You're reading stale information.

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

  useEffect(() => {
    const timer = setInterval(() => {
      console.log(count); // ALWAYS logs 0!
    }, 1000);
    
    return () => clearInterval(timer);
  }, []); // Missing dependency: count

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

Even though count updates on screen, the interval keeps logging 0 because it captured count from the first render and never updated.

Why It Happens

JavaScript closures remember the variables from when the function was created. With an empty dependency array, the effect runs once and closes over the initial values forever. Those values become "stale."

The Fix

List count as a dependency so the effect re-runs with fresh values:

useEffect(() => {
  const timer = setInterval(() => {
    console.log(count); // Now logs current count!
  }, 1000);
  
  return () => clearInterval(timer);
}, [count]); // Include the dependency

Now every time count changes, the effect cleans up and re-runs with the new value.

Key Takeaway: Missing dependencies create stale closures where your effect uses outdated values. Always include every prop or state variable your effect reads—the exhaustive-deps ESLint rule catches these bugs for you.