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

138
Visualizações
I am not able to figure out why these two pieces of code work differently

This piece of code works fine and increments the count every second.

import React, { useEffect, useState } from 'react'

function IntervalHookCounter() {
  const [count, setCount] = useState(0)
  const tick = () => {
      console.log("Called tick")
      setCount(prevCount => prevCount+1)
  }

  useEffect(() => {
      const interval = setInterval(tick, 1000)
      return () => {
          clearInterval(interval)
      }
  }, [])
  return (
    <div>
        <h1>{count}</h1>
    </div>
  )
}

export default IntervalHookCounter

But this piece of code only goes up 1 count and then stops

import React, { useEffect, useState } from 'react'

function IntervalHookCounter() {
  const [count, setCount] = useState(0)
  const tick = () => {
      console.log("Called tick")
      setCount(count+1)
  }

  useEffect(() => {
      const interval = setInterval(tick, 1000)
      return () => {
          clearInterval(interval)
      }
  }, [])
  return (
    <div>
        <h1>{count}</h1>
    </div>
  )
}

export default IntervalHookCounter

Any idea why this might be the case. Please help this is getting really confusing.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The first code block - is using the previous state to increment the count, i.e. Take the previous value and increment by 1. Prev state is updated in the callback

In your second code block, - setCount(count+1) doesn't have access to the new count value in the subsequent render because the useEffect() is not invoked the second time. count always has the value of 0 within the setInterval callback, (0 is the default state)

about 4 years ago · Juan Pablo Isaza Relatório

0

This line screws you over: setCount(count+1)

cause count is constant from outer scope and it is always 0 (even if it was let you never reassign it) so effectively you end up always with 0+1 in 2nd example

cheers!

about 4 years ago · Juan Pablo Isaza Relatório

0

this has to do with closures.

  • In short the first tick make sure that we add 1 to the previous state each second.

  • the Second add 1 to count and for the function tick the count is always 0 (the first value of the count) so the function is fired every second but count + 1 is always 1 because count is always 0 for the tick function

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