Reputation:
I'm new to React, just a question on setState(), below is a component:
...
handleEvent = (event) => {
this.setState({greeting: 'Hello'});
}
render() {
...
<button onClick={ this.handleEvent }>Click</button>
I was told React apply changes asynchronously, my questions are:
Q1- does it mean that the component's state will not be updated before the handleEvent function finishes? and the state will only get updated some time after handleEvent function finishes?
Q2- By the meaning of asynchronously, it means changes could happen any time, so does it still means that state changes still possible apply before handleEvent function finishes? it just a matter of probability, which is most of times state changes apply after callback function finishes?
Upvotes: 1
Views: 53
Reputation: 138267
Q1 - Yes.
Q2 - No. JS functions have a run to completion guarantee. In other words: As long as the handleEvent
function runs, no other function will run. The state update will definetly happen afterwards.
Upvotes: 4