title: React setTimeout with Loop
body: <p>I am pulling documents from Firebase, running calculations on them and separating the results into an array.  I have an event listener in place to update the array with new data as it is populated.</p>
  <p>I am using setTimeout to loop through an array which works perfectly with the initial data load, but occasionally, when the array is updated with new information, the setTimeout glitches and either begins looping through from the beginning rather than continuing the loop, or creates a visual issue where the loop doubles.</p>
  <p>Everything lives inside of a useEffect to ensure that data changes are only mapped when the listener finds new data.  I am wondering if I need to find a way to get the setTimeout outside of this effect?  Is there something I'm missing to avoid this issue?</p>
  <pre class="lang-javascript prettyprint-override"><code>const TeamDetails = (props) =&gt; {
  const [teamState, setTeamState] = useState(props.pushData)
  const [slide, setSlide] = useState(0)
  
  useEffect(() =&gt; {
    setTeamState(props.pushData)
  }, [props.pushData])
  
     
    useEffect(()=&gt; {
  
    const teams = teamState.filter(x =&gt; x.regData.onTeam !== &quot;null&quot; &amp;&amp; x.regData.onTeam !== undefined)
    const listTeams = [...new Set(teams.map((x) =&gt; x.regData.onTeam).sort())];
   
    
    const allTeamData = () =&gt; {
  
     
      let array = []
      listTeams.forEach((doc) =&gt; {
        //ALL CALCULATIONS HAPPEN HERE
      }
      array.push(state)
      })
      return array
    }
  
  
  function SetData() {
    var data = allTeamData()[slide];
    //THIS FUNCTION BREAKS DOWN THE ARRAY INTO INDIVIDUAL HTML ELEMENTS
  } 
  
  
  
  SetData()
  
  setTimeout(() =&gt; {
    if (slide === (allTeamData().length - 1)) {
      setSlide(0);
    }
    if (slide !== (allTeamData().length - 1)) {
      setSlide(slide + 1);
    }
    SetData();
      console.log(slide)
    }, 8000)
  }, [teamState, slide]);
  </code></pre>