Skip to content
Advertisement

What’s going on with React’s useState?

So here is Piece of Code for onClick EventHandler in React

code :

function handleChange(event) {
console.log('before 1st update')

setCount(prevCount => {
  console.log('inside 1st update')
  return prevCount + 1
})

console.log('After 1st update')

setCount(prevCount => {
  console.log('inside 2nd update')
  return prevCount + 1
})

console.log('After 2nd update')}

Output :

before 1st update
inside 1st update
After 1st update
After 2nd update
inside 2nd update

Expected Output :

before 1st update
inside 1st update
After 1st update
inside 2nd update
After 2nd update

Could Someone Explain? Also, The example provides decent enough evidence that the updater function is synchronous and updation is asynchronous(in the case of Browser Events).

Advertisement

Answer

setState in React acts like an async function.
So putting a console.log(state) right after setting it, will most likely show the former value, as it doesn’t actually finish updating the state until the log command runs.
What we can do to act upon a change in state, is use React’s built-in useEffect hook that has the relevant state as a dependency to check the value.

Example:

useEffect(() => {
   console.log(state);
}, [state]);

Basically, the callback function in the example will run every time the state changes.

In your case, it should look like this:

function handleChange(event) {
   console.log('before 1st update')

   setCount(prevCount => {
      console.log('inside 1st update')
      return prevCount + 1
   })

   setCount(prevCount => {
      console.log('inside 2nd update')
      return prevCount + 1
   })
}

useEffect(() => {
   console.log('count has been updated:', count)
}, [count])

The rest of the logs are valid.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement