Home > OS >  Setting state in useEffect hook does not change state value
Setting state in useEffect hook does not change state value

Time:12-21

am writing an app in react native and i got a problem with useState and useEffect hooks. I would like to change increment state value by one every 10 seconds.

Here is my code:

const [tripDistance, setTripDistance] = useState(0);

useEffect(() => {
  const interval = setInterval(() => {
    setTripDistance((prevState) => prevState   1);

    console.log(tripDistance);
  }, 10000);
  return () => {
    clearInterval(interval);
  };
}, []);

but the output from the console.log is always 0.

What am I doing wrong?

CodePudding user response:

The output is always zero because in your useEffect you are not listening for the changes on tripDistance state. When you call setTripDistance you cannot access the updated value immediately.

You should add another useEffect that listen on tripDistance in order to have the correct console.log.

So you have to do something like:

const [tripDistance, setTripDistance] = useState(0);

useEffect(() => {
  const interval = setInterval(() => {
    setTripDistance((prevState) => prevState   1);
  }, 10000);
  return () => {
    clearInterval(interval);
  };
}, []);
useEffect(() => console.log(tripDistance), [tripDistance]);
  • Related