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

126
Visualizações
React stale state with useEffect loop

Given the following component:

import { useEffect, useState } from "react"

const Test = () => {
    const [thing, setThing] = useState({ x: 0, y: 0 });
    useEffect(() => {
        gameLoop();
    }, []);

    const gameLoop = () => {
        const p = {...thing};
        p.x++;
        setThing(p);
        setTimeout(gameLoop, 1000);
    }

    return (
        <div>

        </div>
    )
}

export default Test;

Every second a new line is printed into the console. The expected output should of course be:

{ x: 1, y: 0 }
{ x: 2, y: 0 }
{ x: 3, y: 0 }

...etc

What is instead printed is:

{ x: 0, y: 0 }
{ x: 0, y: 0 }
{ x: 0, y: 0 }

I've come to the conclusion as this is because of a stale state. Some solutions I've found and tried are:

  1. The dependency array

Adding thing to the dependency array causes it to be called ridiculously fast. Adding thing.x to the array also does the same.

  1. Changing the setState call

One post I found mentioned changing the setState to look like so:

setState(thing => {
    return {
        ...thing.
        x: thing.x+1,
        y: thing.y
 });

Which changed nothing.

I have found a lot of posts about clocks/stopwatches and how to fix this issue with primitive value states but not objects.

What is my best course of action to fix the behavior while maintaining that it only runs once a second?

EDIT: The comments seem to be stating I try something like this:

import { useEffect, useState } from "react"

const Test = () => {
    const [thing, setThing] = useState({ x: 0, y: 0 });
    useEffect(() => {
        setInterval(gameLoop, 1000);
     }, []);
     
     const gameLoop = () => {
        console.log(thing)
        const p = {...thing};
        p.x++;
        setThing(prevP => ({...prevP, x: prevP.x+1}));
     }

    return (
        <div>

        </div>
    )
}

export default Test;

This still prints out incorrectly:

{ x: 0, y: 0 }
{ x: 0, y: 0 }
{ x: 0, y: 0 }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you can use this solution:

useEffect(() => {
    setInterval(() => {
      setThing((prev) => ({
        ...prev,
        x: prev.x + 1,
      }));
    }, 1000);
  }, []);

I suggest to control setInterval with the clearInterval when component is destroied; like this:

useEffect(() => {
    const interval = setInterval(() => {
      setThing((prev) => ({
        ...prev,
        x: prev.x + 1,
      }));
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, []);
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