title: How to correctly set state in a loop in react functional component using useState
body: <p>Consider I'm uploading a bunch of files and I'm trying to keep track of the ones in progress so that whenever an upload is finished, I decrement my state until all are finished and finally I change my uploading state to <code>false</code>:
   (Here I made a <code>sleep</code> function to mimic the uploading process).</p>
  
  <pre class="lang-js prettyprint-override"><code>import React, { useState} from "react";
  
  const sleep = (ms, dev =1 ) =&gt; {
    const msWithDev = (Math.random() * dev + 1) * ms
    return new Promise(resolve =&gt; setTimeout(resolve, msWithDev))
  }
  
  function Counter() {
    const [, setSortEnabled] = useState(true)
    const [count, setCount] = useState(0)
    const arr = [1, 2, 3, 4, 5]
  
    const upload = async () =&gt; {
      await sleep(1000)
      setCount(c =&gt; c - 1)
  
        console.log(`count state: ${count}`)
  
        if (count === 0) {
          console.warn('Sort set to enabled again.')
          setSortEnabled(true)
      }
    }
  
  
    const onClick = ()  =&gt; {
      console.warn('Sort set to disabled.')
        arr.forEach(item =&gt; {
          setCount(c =&gt; c + 1)
          console.error(count)
          upload()
        })
      }
  
    return (
      &lt;&gt;
      &lt;button onClick={onClick}&gt;Click me!&lt;/button&gt;
      &lt;/&gt;
    );
  }
  
  export default Counter;
  </code></pre>
  
  <p>The problem is in <code>upload</code>,</p>
  
  <pre><code>function `console.log(\`count state: ${count}\`)`
  </code></pre>
  
  <p>always logs <code>0</code> which means the state has never been updated.</p>
  
  <p>What am I doing wrong here?</p>