title: Why do my state update not impact another function currently running?
body: <p>I am building a piece of code in which I need 2 nested components to update a state variable:</p>
  <pre><code>function Test() {
      const [test, setTest] = useState()
  
      async function wait() {
          await new Promise((res, rej) =&gt; setTimeout(res, 1000))
          console.log(&quot;after 1s waiting, test is&quot;, test)
      }
  
      async function setTest1() {
          await wait()
          setTest(&quot;test1&quot;)
      }
  
      async function setTest2() {
          setTest(&quot;test2&quot;)
      }
  
      useEffect(() =&gt; console.log(&quot;after being updated, test is&quot;, test), [test]);
  
      return (
          &lt;div&gt;
              &lt;div onClick={setTest1}&gt;
                  &lt;span onClick={setTest2}&gt;update test&lt;/span&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      )
  }
  </code></pre>
  <p>When clicking &quot;update test&quot;, <code>setTest2</code> is called then <code>setTest1</code> is called. This happens asynchronously: <code>setTest1</code> might be called before <code>setTest2</code> ends.</p>
  <p>First, <code>setTest2</code> and <code>setTest1</code> are called. Then <code>setTest2</code> updates <code>test</code>, giving it the value <code>&quot;test2&quot;</code>. At this point <code>setTest1</code> is still running. It is waiting 1s before continuing. After 1s, the value of <code>test</code> is undoubtedly <code>&quot;test2&quot;</code>. Is it not?...</p>
  <p>When logging the value of <code>test</code> after waiting 1s, I would expect the result to be <code>&quot;test2&quot;</code>, since the state has already been updated to <code>&quot;test2&quot;</code>. However, the result is not <code>&quot;test2&quot;</code>, but <code>undefined</code>, as if it had not been updated by <code>setTest2</code>.</p>
  <p>This piece of code logs this:</p>
  <pre><code>after being updated, test is undefined
  after being updated, test is test2
  after 1s waiting, test is undefined &lt;--- what ???
  after being updated, test is test1
  </code></pre>
  <p>It looks like some kind of scoping mechanism, but I am unable to find an explanation for it.</p>
  <p>Why is <code>test</code>'s value not <code>test2</code> when logged in the <code>wait</code> call inside of the <code>setTest1</code> call?</p>