title: Is it possible to make a recursive function in React that can be passed in state
body: <p>I'm trying to render items from an array stored in state one at a time to the screen.  After an item is displayed on the screen it is removed from the array, then the next item is displayed and so on until there are no items left in the array.  The catch that has me sprung is that items can be added to the array via websockets while the function is already running. So essentially I want to create a live item queue. When an item or items are added to the queue, I want to the function to trigger and display the items on screen one by one until the queue is empty.</p>
  <p>I thought using a recursive function that could initially be triggered by a useEffect might work. But what's weird is that inside my animateDisplay function the value for items never changes, but outside the function it changes like expected.  It's like the value for items is cached within the recursive function.  So my function repeats forever:</p>
  <pre><code>console.log(`outside ${items}`) // If items started as [1,2,3] it would log [1,2,3] then [2,3] then [3] on each render
  
  const animateDisplay = async () =&gt; {
      running.current = true
      setDisplay(items[0])
      await timeout(4000)
      setDisplay({})
      setItems(prevState =&gt; prevState.slice(1))
  
      console.log(`inside ${items}`) // If items started as [1,2,3] it would log [1,2,3] on every render
  
      if (items.length &gt; 0) {
          await timeout(4000)
          await animateDisplay()
      }
      running.current = false
  }
  
  useEffect(() =&gt; {
      if (running.current === false &amp;&amp; items.length &gt; 0) {
          animateDisplay()
      }
  }, [items])
  </code></pre>
  <p>Is there anyway I can achieve what I am after?</p>