kubas1178
kubas1178

Reputation: 41

Setting state in useEffect hook does not change state value

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?

Upvotes: 0

Views: 1407

Answers (2)

Sukma Dewa
Sukma Dewa

Reputation: 21

try this

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

  useEffect(() => {
    const interval = setInterval(() => {
      setTripDistance((prevState) => prevState + 1);
    }, 10000);
    return () => {
      clearInterval(interval);
    };
  }, [tripDistance]);

Upvotes: 0

Marco Nisi
Marco Nisi

Reputation: 1241

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]);

Upvotes: 2

Related Questions