score:2

Accepted answer

Test only has one setInterval function where count is always 0. Since it's only created during initial render.

It never had another setInterval created because the effect never got triggered with [props] as the dependency.

To have setInterval's count change on every re-render:

  • Remove the dependency
  • Return a clean-up function inside the effect
useEffect(
  () => {
    const t = setInterval(() => {
      console.log("count in interval is:", count);
    }, 1000);

    return () => clearInterval(t); // cleanup on every re-render
  }
  // no dependency: effect runs on every re-render
);

But the above code will have a warning:

"missing count dependency"

So simply add count as dependency to only run the effect when count changes.

useEffect(
  () => {
    const t = setInterval(() => {
      console.log("count in interval is:", count);
    }, 1000);

    return () => clearInterval(t); // cleanup "old" setInterval
  }
  , [count] // ony run effect every time count changes
);

score:0

The value of count doesn't change, this is the expected behavior, though not an obvious one.

See, you even declare count as a const count, it is immutable. What is happening instead is that during the first render count gets assigned value of 0. The value of count never changes, what happens instead is that component Test is called each time you change the state, and function useState assigns different values to the constant count, which is new constant every time.

So during the first render the value of const count gets captured by closure inside your function that is called by setInterval and the value stays 0 forever.


Related Query

More Query from same tag