So I read a lot that setState calls are batched and are async, and that one should use the updater function to update state when any value is read from the state in setState
.
class App extends React.Component {
state = { count: 1 }
handleClick = () => {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<div>
<div>{this.state.count}</div>
<button onClick={this.handleClick}>Click</button>
</div>
)
}
}
Considering above code ONLY, can someone explain what might go wrong in this case by not using the updater pattern of setState
? Even if setState
is called later, this.state
will always refer to previous state, which is what we want here.
PS: I know that calling setState
multiple times one after the other will cause errors in this kind of scenario because they are async, but that's not the case here.