Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting.
setState updates asynchronously. It updates in batches to improve the performance of React app. In order to understand more, click here to read more on difference between passing function and passing object to setState
Because setState
is asynchronous, if you update state multiple times by passing object to setState
, then the updates will be missed.
Lets take an example where we pass object to setState function.
class Example extends React.Component{
state = {
no: 0
}
componentDidMount(){
this.incrementNo();
this.incrementNo();
this.incrementNo();
}
incrementNo(){
this.setState({
no: this.state.no + 1
})
}
render(){
return <div>Value of no: this.state.no</div>;
}
}
In the above Example
component, we have initialized state variable no
with value as 0. On mount of the component, we increment the number by 1. We are passing object to the setState function. We increment no by following code.
this.setState({
no: this.state.no + 1
})
Initially, the value of no will be 0. Because we are getting the state by this.state
, it will not give the latest value always. The React will update the state in batch. So at the end of three incrementNo functions, the state of the no
will be 1.
Value of no: 1
In order to solve the above problem, we will access the state of "no" variable using previous state, and not by this.state
So lets change the incrementNo function as follows
incrementNo(){
this.setState((prevState)=>({
no: prevState.no + 1
}))
}
At the end, the value of "no" will be 3
Value of no: 3
It is not necessary to pass function to the setState function always. Only when you are accessing previous state inside setState
function by this.state
, it is necessary to use prevState
. Because this.state
will not give latest value.