0
import React, {useState} from "react";
import ReactDOM from "react-dom";

function App() {
  const [test, setTest] = useState("red");

  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
  const hello = async () => {
    setTest("green");
    await sleep(2000);
    console.log(test)      // prints red
  }

  return (
    <div className="App">
      <h1>Test Bed React Code Change B</h1>
      <button onClick={hello}> test</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

In this minimal example, I would expect console.log(test) to output "green" but it outputs "red" (on the first button click). I know setTest is async but it should have time to apply while sleeping for 2 seconds.

I'm sure it's a really basic question but I couldn't find a proper answer.

RobIII
  • 8,488
  • 2
  • 43
  • 93
aurelien_morel
  • 444
  • 3
  • 14
  • 2
    No matter how long you will wait `const test` will always have the same value because it's constant. When state is changed `App` function will be called again and then the values will change – Konrad Mar 26 '23 at 15:29
  • yes thanks a lot it's interesting, I thought it was only a matter of time but actually not – aurelien_morel Mar 26 '23 at 15:50

1 Answers1

1

The value will not change until the component updates. You called the function, therefore it will run once with the 'test' state as the value it was upon being called.

If you want to log the value after it has changed consider the following change using Reacts 'useEffect'

function App() {
  const [test, setTest] = useState("red");

  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
  const hello = async () => {
    setTest("green");
  }
  
  useEffect(() => {
      console.log(test)

  // 'test' dependency means above code ^ will only run whenever 'test' changes
  }, [test]);

  return (
    <div className="App">
      <h1>Test Bed React Code Change B</h1>
      <button onClick={hello}> test</button>
    </div>
  );
}

You will also need to import useEffect as so:

import React, {useState, useEffect} from "react";
Kalaghni
  • 46
  • 1