How to manage the asynchrounous nature of useState hook when setting a value and using it directly after

mottosson :

I'm new to React and can't really understand how to use the useState hook correctly.

export default function App() {
  const [name, setName] = useState("noname");

  const updateAndLogName = () => {
    setName("Alex");
    console.log(name); // first time => "noname"
  };

  return (
    <div className="App">
      <button onClick={() => updateAndLogName()}>
        Click me to change and log name in console
      </button>
    </div>
  );
}

CodeSandbox 1

I call a method that updates the value and uses the updated value directly after. But since the setName function is asynchronous I get the original value in the console.log and have to wait until React has updated the value to get the correct result.

In this simplified example I could just take the value as a function argument and use it in both the setName and console.log, and maybe that's the way it should be done, but are there any other preferred way to handle this situation?

EDIT:

Here is another example:

CodeSandbox 2

giorgim :

In this simplified example I could just take the value as a function argument and use it in both the setName and console.log, and maybe that's the way it should be done

That is one way if you don't want to wait for another render. If waiting for a render is okay, another way could be:

useEffect(()=>{
  console.log("Will get here anytime name changes", name);
}, [name])

Also related.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29799&siteId=1