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;