With class-based components, I can (for example) do this:
doThing = () => {
this.setState({
test: 'Zest'
})
setTimeout(() => {
console.log(this.state.test) // will return 'Zest'
},1000)
}
However, in a functional component with the useState
hook, the state won't be updated until another event listener is called. My example is most obvious when using setTimeout
listener, but it shows up in lots of other contexts too.
Once an event listener is called, no state updates are received until another one's called.
Up until now, every time this weird quirk has caused any issues I just change the component back to a class-based one, but I've always wondered what it was about.
Can anyone explain why or offer a means of getting an updated state within a callback/timeout/interval/etc using a functional component and react hooks?