Please, help to understand the essence of how React setState
actually works.
Here is example:
class App extends React.Component { // first example
state = {
clicks: 0
};
handleButtonClick = this.handleButtonClick.bind(this);
handleButtonClick() {
this.setState({ // like this? Or should we use callback instead of object?
clicks: this.state.clicks + 1
});
}
render() {
return (
<div>
<div>Count: {this.state.clicks}</div>
<button onClick={this.handleButtonClick}>Click</button>
</div>
);
}
}
if we call setstate multiple times, we should use callback:
this.setState(prevState => ({ // second example
clicks: prevState.clicks + 1
}));
this.setState(prevState => ({
clicks: prevState.clicks + 1
}));
and calls will be like: setState
then setState
.
But in first example we have one call setState
:
Click then setState
then click then setState
.
You see? In first example we have CLICK between setState
.
In second example we does not have click, we have immediately call one by one.
Question: Should we use callback instead of object? Why? Now all work properly.
I searched for the answer on the Internet for a long time but did not find good arguments on this case.
P.S. sorry for my bad English.