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

355
Visualizações
Nextjs: update state not work in interval

This is my state:

const [time, setTime] = useState(10)

And this is my handler:

const runTimer = () => {
    useEffect(() => {
        const interval = setInterval(() => {
            console.log(time)
            if (time > 0) {
                setTime(time - 1)
            } else {
                console.log("End")
            }
        }, 1000);
        return () => clearInterval(interval)
    }, [])
}

My log:

9
9
9
9
9
.
.
.

Why setTime doesn't work ?

time variable most increase per 1000 delay

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

0

The function you pass to useEffect has closed over the timer variable from the first time the component rendered.

Each time the component renders, the current value of the state is read and a timer variable is created with that value.

You aren't accessing that variable though. The variable you are accessing on the interval never changes, so every time you access it, it is still 10.


State functions are passed the current value as an argument, so use that instead.

const Timer = () => {
    const [timer, setTime] = useState(10);
    useEffect(() => {
        const interval = setInterval(() => {
            setTime(
                (currentTime) => {
                    if (currentTime > 0) {
                        return currentTime - 1;
                    } else {
                        console.log("End of interval");
                        clearInterval(interval);
                        return currentTime;
                    }
                }
            );
        }, 1000);
        return () => clearInterval(interval)
    }, [])
    return <p>{timer}</p>
}
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