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

106
Visualizações
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 Respostas
Responde à pergunta

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