Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda