title: why does setInterval close over state variable but not instance variable
body: <p>I am trying to log the value of a state variable at specific time intervals. What I observed is that the setInterval closes over the state variable and stale value is logged. But if I use 'ref' instance variable created by useRef, it logs latest value correctly, which means setInterval does not close over ref instance variables. So my question is why does setInterval close over state variable but not instance variable. Here is <a href="https://codesandbox.io/s/setinterval-closure-question-6qom5" rel="nofollow noreferrer">codesandbox</a> .</p>
  <pre><code>import React, { useState, useEffect, useRef } from &quot;react&quot;;
  
  export default function App() {
    const [count, setCount] = useState(0);
    let val = useRef(0);
  
    const handleClick = () =&gt; {
      setCount((count) =&gt; {
        return count + 1;
      });
    };
  
    useEffect(() =&gt; {
      val.current = count;
    }, [count]);
  
    useEffect(() =&gt; {
      let handle = setInterval(log, 5000);
  
      return () =&gt; clearInterval(handle);
    }, []);
  
    const log = () =&gt; {
      console.log(count); //stale value
      console.log(val.current); // latest value
    };
  
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;p&gt;{count}&lt;/p&gt;
        &lt;button onClick={() =&gt; handleClick()}&gt;Add 1 &lt;/button&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>