0

I am trying to update some data on my website roughly once per second. Since I have been getting some strange behaviour, I added a counter to see what was happening. I have used google and tried suggestions, but most seem to reference setState, not useState. I also came across seemingly conflicting information, some saying that useState triggers a rerender and others stating that the effects of useState are only "visible" after a rerender.

The result I am getting in the logs is that count is continuously 0, while localCount goes up. At some point I have looked at other tabs and must have done something to make the app rerender, because count was suddenly over 1000 (and staying at that number again), while localCount had started from 0 again.

I don't need localCount of course, if I could reliably use setCount() to update the count every second. But that has never worked for me. Updating the count in this way did work in the past. I am not sure what I changed that means it no longer does now.

Can I make sure that setCount() actually changes the count? Is the problem that I am trying to do it from an interval, and if so, is there a fix I can do?

The counter code I have looks like this:

function App() {
  const [count, setCount] = useState(0);

  const everyTick = (count: number) => {
    setCount(count);
  }
  
  useEffect(() => {
    let localCount = 0;
      let timer1 = setInterval(() => {
        everyTick(localCount);
        localCount++;
        console.log("localCount", localCount)
        console.log("count", count);
      }, 1000)
      return () => {
        clearInterval(timer1);
      };
  }, [])  

  return (
    // the html
  );
}

export default App;
KKie
  • 21
  • 2
  • 1
    You are using stale value due to JS closures, `localCount` value is `0` in interval's callback closure. Please refer to duplicate question or research similar interval questions, its a common mistake. – Dennis Vash Jul 14 '22 at 13:17
  • I have tried the suggestion made in the other answer (`setCount((count) => count+1)` but it did not help. My count remains 0 wherever I check it. I have a `useEffect` method elsewhere that has `count` in the dependancy array and it does run every time count "changes", but the value of count remains 0. – KKie Jul 15 '22 at 04:53
  • For testing I am now showing the count on screen, and it does update. It is just within the code (console.logs and calculations) where count appears to remain 0. – KKie Jul 15 '22 at 04:59
  • Just put the example in codesandbox as simple as it – Dennis Vash Jul 17 '22 at 06:56

0 Answers0