Special oddness with useState()/useEffect()

This is interesting/weird.  The following code does NOT work:

const [refresh, setRefresh] = useState(10);
useEffect(() => {
setInterval(() => {
console.log(“Timeout, refresh:”, refresh);
setRefresh(refresh + 3);
}, 1000);
return list.unsubscribe;
}, []);

What happens is that each time the timer-interval goes off, the value of ‘refresh’ is still at 10. Why?

The value goes to 13, once.  Then, each time it goes from 10 to 13 and because 13 was the prior value (per what React thinks) my component doesn’t refresh.

I *believe* it has something to with the stack that is calling this.  Mind you, if i just put that setInterval or setTimer in the body of my functional component, it works fine.  I’m really not sure what is going on.  I also think that if I used a class component and thus this.state.refresh that it night work fine (why? be ‘refresh’ is no longer a copy-of a value but actually referenced inside an object tree).  


Leave a Comment

Your email address will not be published. Required fields are marked *