title: Why does listing a variable as a dependency "solve" the stale closure problem?
body: <p>I'm trying to understand the general advice I've seen regarding <a href="https://dmitripavlutin.com/react-hooks-stale-closures/" rel="nofollow noreferrer">React and stale closures</a>.</p>
  <p>Specifically, as I understand it, the term &quot;stale closure&quot; is used to describe a scenario where a component and <code>useEffect</code> function are constructed like this</p>
  <pre><code>function WatchCount() {
    const [count, setCount] = useState(0);
  
    useEffect(function() {
      setInterval(function log() {
        console.log(`Count is: ${count}`);
      }, 2000);
    }, []);
  
    return (
      &lt;div&gt;
        {count}
        &lt;button onClick={() =&gt; setCount(count + 1) }&gt;
          Increase
        &lt;/button&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  <p>React calls <code>WatchCount</code> to render a component, and sets the value of the <code>count</code> variable. When javascript calls the <code>log</code> function two seconds later, the <code>count</code> variable will be bound to the <code>count</code> variable from when <code>WatchCount</code> was first called.  The value of <code>count</code> won't reflect updates that may have happened on renders of <code>WatchCount</code> that happened in-between the first render and the interval code eventually firing.</p>
  <p>The general advice that's given to &quot;solve&quot; this is to list your variable in the dependencies array -- the second argument to <code>useEffect</code></p>
  <pre><code>useEffect(function iWillBeStale() {
    setInterval(function log() {
      console.log(`Count is: ${count}`);
    }, 2000);
  }, [count]);
  </code></pre>
  <p>As a javascript programmer, I don't understand how this &quot;solves&quot; the problem.  All we've done here is create an array that includes the variable in it, and passed that array to <code>useEffect</code>  My naive view is that the <code>count</code> variable in <code>log</code> is still scoped to the first call of <code>WatchCount</code>, and should still be stale.</p>
  <p>Am I missing some nuance of javascript's scope here?</p>
  <p>Or does this &quot;fix&quot; things because of something that <code>useEffect</code> is doing with those variables?</p>
  <p>Or some third thing?</p>