Reputation: 53
When we have to update any state which is based on the previous state then it is better to use this.state?
class Counter extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
changeCount() {
this.setState({
count: this.state.count + 1
})
}
}
or it is better to use function?
class Counter extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
changeCount() {
this.setState(prevState => ({
count: prevState.count + 1
}))
}
}
Upvotes: 0
Views: 47
Reputation: 631
The later one is better. Using prevState is better than using this.state for updating states based on previous state values.
As mentioned here: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
One may not across a situation where the difference is clear. But when working with frequent states updates asynchronously, it will be very difficult to debug. Thus it's not good to rely on the former case.
Upvotes: 2