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

Update React State variable inside an Interval

I create this simple example script to animate a player position using a simple setInterval function but impossible to make it works..

Everytime it go into the interval function the playerPos is back to is initial value..

import React, { useEffect, useState } from 'react';

const App = () => {

  let [playerPos, setPlayerPos] = useState({x:128, y:128})

  useEffect(() => {

    setInterval(() => {

      console.log(`Current player pos ${JSON.stringify(playerPos)}`);
      setPlayerPos({x:128, y:playerPos.y + 10});

    }, 1000);

  }, []);

  return <div style={{position: "absolute", top: `${playerPos.x}px`, left: `${playerPos.y}px`}}></div>
}

Strangely, my console only showing:

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

Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
...

What did I misunderstood in hooks and effects ??!

>Solution :

The useEffect only ran once, when the component initially loaded, and at the time only had the initial value of the playerPos state. So you effectively have a closure around that one value that’s just repeating.

Instead of using setInterval, rely on useEffect to run multiple times whenever the state changes by adding that state value to its dependency array. Then just use setTimeout to add the delay each time. For example:

useEffect(() => {
  setTimeout(() => {
    console.log(`Current player pos ${JSON.stringify(playerPos)}`);
    setPlayerPos({x:128, y:playerPos.y + 10});
  }, 1000);
}, [playerPos]);

So each time the component renders, useEffect will re-run if playerPos has changed. And each time it runs, playerPos will be changed one second later, triggering a re-render.

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