I would like to know which form of setState
to use if I want to update the state based on the current state.
React's setState
takes either an object or a function as argument. As I understand, the following does not work as intended because React batches setState
state = {score : 0};
increaseScoreBy2 () {
this.setState({score : this.state.score + 1});
this.setState({score : this.state.score + 1});
}
and it is better to use
increaseScoreBy2 () {
this.setState(prevState => { return { score: prevState.score + 2 }}});
}
But If all I want to do is to update state one time, which form of setState
should be used? Is it a matter of personal preference? Or should we always use functional form when updating state based on the current state to avoid any possible unexpected behavior?
For instance, is there anything wrong with the following code?
const newRegions = this.state.regions.map(...)
this.setState({ regions: newRegions });