简体   繁体   中英

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 }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM