title: How to set a state in a forEach loop using useState hook
body: <p>I want to transfer data in an array A into a object B, so i doing something like [array].forEach(e =&gt; setB({...B, e})), but it seems like when traversing on later elements, former actions have been &quot;forgotten&quot;, how should i achieve my goal?<br>
  Prototype should looks like this:</p>
  <pre><code>import React from &quot;react&quot;
  import {Map} from &quot;immutable&quot;
  
  export default function App() {
      const [arrayA, setA] = React.useState([1, 2]);
      const [objB, setB] = React.useState(Map({}));
      React.useEffect(() =&gt; {
          arrayA.forEach(num =&gt; {
              setB(objB.set(num, num*num));
          })
      }, [])
  
      return (&lt;div&gt;null&lt;/div&gt;)
  }
  </code></pre>
  <p>Thanks in advance!</p>