How to get newly changed value after apply React useState in a handler?

Here is a React code chunk:

const [win, setWin] => useState(false)
const [guessedNumber, setGuessedNumber] => useState(undefined)

const clickHandler = () => {
   setGuessedNumber(randomNumber())

   if(guessedNumber === 10) {
     setWin(true)
   }
}

Explanation: after clicking on button (not presented here) the handler clickHandler fires. Generates random number, setGuessedNumber hook runs. But due to batching the new value of guessedNumber we can find after clickHandler do it works. But I need to see the new value of guessedNumber immediately.

Here is my solution I have done:

const [win, setWin] => useState(false)
const [guessedNumber, setGuessedNumber] => useState(undefined)

const clickHandler = () => {
   const rndNum = randomNumber()

   setGuessedNumber(rndNum)

   if(rndNum === 10) {
     setWin(true)
   }
}

The setGuessedNumber I use for rerender, rndNum for the calculations and logics.

Is it right solution? Or there is something React’ish?

Answer

What you have done in the second example is correct.

const [win, setWin] => useState(false)
const [guessedNumber, setGuessedNumber] => useState(undefined)

const clickHandler = () => {
   const rndNum = randomNumber()

   setGuessedNumber(rndNum)

   if(rndNum === 10) {
     setWin(true)
   }
}

These hooks are asynchronous. They just queue the updates rather than immediately executing them. You can refer this. https://linguinecode.com/post/why-react-setstate-usestate-does-not-update-immediately