title: useState non-instantaneous updates break function
body: <p>I have a <code>sumButtonsDict</code> state variable that stores a dictionary of objects. I've also built a simple <code>addSumButton()</code> function add a new object into the <code>sumButtonsDict</code>:</p>
  <pre><code>const [sumButtonsDict, setSumButtonsDict] = useState({})
  
  function addSumButton(sum) {
      const dictKey = Object.keys(sumButtonsDict).length
      const sumButtonDict = {
          sum: sum,
          isActive: false
      }
      setSumButtonsDict(prevState =&gt; ({...prevState, [dictKey]: sumButtonDict}))
  }
  </code></pre>
  <p>As you can see, the function stores every new dictionary item at a key corresponding to the index it's on (e.g., first item has key 0, second item has key 1...), but the correct key is derived from the count of objects already existing in <code>sumButtonsDict</code>.</p>
  <p>When the component mounts, I add 5 new buttons using the following:</p>
  <pre><code>useEffect(() =&gt; {
      addSumButton(10)
      addSumButton(25)
      addSumButton(50)
      addSumButton(100)
      addSumButton(250)
  }, [])
  </code></pre>
  <p>but only 1 ends up existing in <code>sumButtonsDict</code>. I suspect this is because <code>setState()</code> doesn't update the state variable immediately, and hence when I call <code>Object.keys(sumButtonsDict).length</code> it keeps on returning <code>0</code> even though the <code>addSumButton()</code> has run multiple times before.</p>
  <p>How can I get around this?</p>