title: How do I loop an image carousel with React setState and setInterval?
body: <p>I am trying to set up an image carousel that loops through 3 images when you mouseover a div. I'm having trouble trying to figure out how to reset the loop after it reaches the third image. I need to reset the setInterval so it starts again and continuously loops through the images when you are hovering over the div. Then when you mouseout of the div, the loop needs to stop and reset to the initial state of 0. Here is the Code Sandbox:</p>
  <p><a href="https://codesandbox.io/s/pedantic-lake-wn3s7" rel="nofollow noreferrer">https://codesandbox.io/s/pedantic-lake-wn3s7</a></p>
  <pre><code>import React, { useState, useEffect } from &quot;react&quot;;
  import { images } from &quot;./Data&quot;;
  import &quot;./styles.css&quot;;
  
  export default function App() {
    let timer;
    const [count, setCount] = useState(0);
  
    const updateCount = () =&gt; {
      timer = setInterval(() =&gt; {
        setCount((prevCount) =&gt; prevCount + 1);
      }, 1000);
  
      if (count === 3) clearInterval(timer);
    };
  
    const origCount = () =&gt; {
      clearInterval(timer);
      setCount((count) =&gt; 0);
    };
  
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;div className=&quot;title&quot;&gt;Image Rotate&lt;/div&gt;
        &lt;div onMouseOver={updateCount} onMouseOut={origCount}&gt;
          &lt;img src={images[count].source} alt={images.name} /&gt;
          &lt;p&gt;count is: {count}&lt;/p&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>