Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }

>Solution :

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);
    };
  }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading