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

161
Vistas
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 Respuestas
Responde la pregunta

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 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