Why?
My goal here was to provide a quick solution for anyone that hits this issue too, so I don’t claim to have the deepest understand of what’s going under the hood. That being said, let me take a stab at explaining my best guess…
Count is a primitive variable?
Count is a primitive variable, this means that when passed into other functions, it’s value is passed in — Not a reference to the variable. This means that if the variable changes, the function doesn’t know the new value.
That came to mind first, but I don’t think it’s quite the only story…
React state is immutable
If count was an object (Which is passed by reference), would we still have this issue? I believe so (though I haven’t tested it). That’s because React state is immutable. Even if it was an object, the objects properties wouldn’t be changed with updates and leave the original object reference valid, but rather, the whole object would be replaced — Making any past references to it wrong, and thus, the values stale.
I’m going to leave it there rather than digging in deeper for now, but now you know what you’re experiencing is a stale closures problem, go ahead an google that to learn more.
And if you know more, feel free to add clarifications/corrections in the comments.