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

105
Vistas
React non state variables inside function component are not updated instantly

I know that useState hook of react is asynchronous so if I use useState to store variable and call set function on it, it may not be updated instantly.

However now I am using simple variables to store the value, but still the variable value is not updated. How can I resolve the same?

const List=(props)=>{
    let count = 1;
    const onNextButtonClick = ()=>{
        count  = count +1;
        console.log(count );
        updatePage();
    }
    return (
        //html
    )
}

I see that the value of c is not getting incremented whenever the next button is clicked and I am getting the same value of c on console.

Why is this happening?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

count needs to be stored in state and, because state updates may be grouped and processed asynchronously, you won't see the change until the next render which is where useEffect comes in useful.

const { useEffect, useState } = React;

function Example() {

  const [ count, setCount ] = useState(0);

  function onNextButtonClick() {
    setCount(count + 1);
    // the other thing
  }

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={onNextButtonClick}>
        Click me
      </button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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