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

103
Visualizações
Why does running a callback from useEffect print the wrong value

I'm trying to understand this weird behavior:

  const [counter, setCounter] = useState<number>(1);
  useEffect(() => {
    setCounter(2);

    setTimeout(function () {
      console.log('counter = ', counter); // => counter = 1
    }, 1000);
  }, []);
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your effect will be called when your component is first mounted, cause you're passing empty array of deps ... where your counter variable is 1

setCounter function is an async function, react-native ui will push that call into the stack of function-calls that's supposed to be called in order, but the the first function call pushed into that stack of calls is your console.log, with a copy of the value of counter variable which is 1

If you want to print the updated value of counter, put counter to the list of deps like:

const [counter, setCounter] = useState<number>(1);
useEffect(() => {
  setCounter(2);
}, []);
useEffect(() => {
  setTimeout(function () {
    console.log('counter = ', counter); // => counter = 1
  }, 1000);
}, [counter]);
about 4 years ago · Santiago Trujillo Relatório

0

What is worth mentioning, you are using counter state value inside useEffect. This is targeted by ESLint with default settings. Your useEffect depends on that state and it should be added to dependency array.[ESLint error][1]

This correct usage of useEffect would cause useTimeout to run 2 times. On initial render and after rerender. [1]: https://i.stack.imgur.com/yiLJi.png

about 4 years ago · Santiago Trujillo 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