Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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).

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda