Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!