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

158
Visualizações
useState setState not updating the state after calling setState

In my react project, using useState hook's setState is not changing my state value, after calling setState.

const [name, setName] = useState("Old");

useEffect(()=>{
    setName("New");

    console.log(name);  //Always prints "Old"
})

I tried adding a callback to setName, but it wouldn't accept that too.

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

0

I finally used the useEffect hook

Since setState is asynchronous, it was not updating the state immediately on call, it rather initiates the process of changing the state and javascript proceeds to execute to the lines below.

So I ended up using useEffect hook to execute anything that I wanted to run after the state name is changed, adding the state name as a dependency as shown below.

const [name, setName] = useState("Old");

useEffect(()=>{
    setName("New");
})


useEffect(()=>{

    console.log(name);  // This Always gets the new value
}, [name])
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