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

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

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 Denunciar

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 Denunciar

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