title: React hooks state in single useEffect
body: <p>I'm trying to use new React hooks capabilities, but stumbled a bit.</p>
  
  <p><a href="https://jsfiddle.net/nidu/8fs7govr/1/" rel="nofollow noreferrer">Fiddle</a></p>
  
  <p>I have a <code>useEffect</code> which calls <code>setInterval</code>, which updates local state. Like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>  const [counter, setCounter] = React.useState(0);
  
    React.useEffect(() =&gt; {
      const k = setInterval(() =&gt; {
          setCounter(counter + 1);
      }, 1000);
      return () =&gt; clearInterval(k);
    }, []);
  
    return (
      &lt;div&gt;Counter via state: {counter}&lt;br/&gt;&lt;/div&gt;
    );
  </code></pre>
  
  <p>It doesn't work right, because counter is captured on first call and so counter is stuck at <code>1</code> value.</p>
  
  <p>If i use refs, ref is updated, but rerender is not called (will only see 0 value in UI):</p>
  
  <pre class="lang-js prettyprint-override"><code>  const counterRef = React.useRef(0);
  
    React.useEffect(() =&gt; {
      const k = setInterval(() =&gt; {
        counterRef.current += 1;
      }, 1000);
      return () =&gt; clearInterval(k);
    }, []);
  
    return (
      &lt;div&gt;Counter via ref: {counterRef.current}&lt;/div&gt;
    );
  </code></pre>
  
  <p>I can make what i want by combining them, but it really doesn't look right:</p>
  
  <pre class="lang-js prettyprint-override"><code>  const [counter, setCounter] = React.useState(0);
    const counterRef = React.useRef(0);
  
    React.useEffect(() =&gt; {
      const k = setInterval(() =&gt; {
          setCounter(counterRef.current + 1);
        counterRef.current += 1;
      }, 1000);
      return () =&gt; clearInterval(k);
    }, []);
  
    return (
      &lt;div&gt;Counter via both: {counter}&lt;/div&gt;
    );
  </code></pre>
  
  <p>Could you please tell who to handle such cases properly with hooks?</p>