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

149
Visualizações
Why is setState not updating my state value?

function LoginComponent(){
  const [clicked, setClicked] = useState(false)
  
  function handleClick(){
    console.log('before', clicked)
    setClicked(true)
    console.log('after', clicked)
  }
  return(
    <a onClick={handleClick}>
      random text
      </a>
  )
}

When I run this, the console outputs before false after false. Why is this? I have no clue why this behavior is like this.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Because setting state is an asynchronous action. It takes some time to update. Check react documentation link to know more

You can check the updated value by

    useEffect(()=> { 
         console.log("clicked", clicked);
 },[clicked]);
about 4 years ago · Juan Pablo Isaza Relatório

0

There are couple of reasons for this behavior:

  • State is updated asynchronously
  • In any particular render, state and props don't change, changes are only reflected when component re-renders

If you want to log the updated value of clicked, put the log statement in the useEffect hook.

You can't update and log the updated value of any state variable in the same render. Component will have to re-render to reflect changes due to state update.

Similarly, if you want to call a function with the updated value of clicked, call the function from inside the useEffect hook.

about 4 years ago · Juan Pablo Isaza Relatório

0

setClicked is asynchronous. You must check the state updated in useEffect

function LoginComponent(){
  const [clicked, setClicked] = useState(false)
  
  function handleClick(){
    setClicked(true)
  }

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

  return(
    <a onClick={handleClick}>
      random text
      </a>
  )
}
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