title: How to Setup a setInterval Timer Properly in a React Functional Component?
body: <p>I have just started learning react and I was watching a tutorial which deals with state and hooks. It just deals with updating time every 1000 milliseconds (or so I thought).</p>
  <pre><code>import React from &quot;react&quot;;
  let count = 0;
  
  function App() {
    const now = new Date().toLocaleTimeString();
    let [time, setTime] = React.useState(now);
  
  
    function updateTime(){
      const newTime = new Date().toLocaleTimeString();
      setTime(newTime);
      count++;
      console.log(count);
      console.log(new Date().getMilliseconds());
    }
  
    setInterval(updateTime, 1000);
  
  
    return (
      &lt;div className=&quot;container&quot;&gt;
        &lt;h1&gt;{time}&lt;/h1&gt;
        &lt;button onClick = {updateTime}&gt;time&lt;/button&gt;
      &lt;/div&gt;
    );
  }
  
  export default App;
  </code></pre>
  <p>The purpose of the tutorial was just a simple example on how to update time, but what I noticed is that it is updated multiple times (in bursts) every 1000 milliseconds. I am suspecting that each time change to a hook happens new component is rendered but the old component is still there updating and spawning more components resulting in what seems like exponential growth of calls every 1000 milliseconds.</p>
  <p>I am very curious what is happening here? How would I go about lets say having a simple counter that updates every 1000 milliseconds? <code>setTime(count)</code> obviously does not work</p>