Why do we have a callback in setState
?
I am new to react and I am trying to understand but I am not able to understand fully.
increasePrice = () => {
this.setState({
price: this.state.price + 1
})
this.props.getPriceData(this.state.price)
}
setstate is async process;its not updated example if you want to pass the data after modified you need to use callback as below
increasePrice = () => {
this.setState({
price: this.state.price + 1
},()=>{
this.props.getPriceData(this.state.price)
})}
As mentioned in the doc: https://reactjs.org/docs/react-component.html#setstate
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
You should never modify the state object directly, but instead use the updater function provided by setState()
:
// Bad
this.state.counter = this.state.counter + this.props.step;
// Good
this.setState((state, props) => {
return {
counter: state.counter + props.step
};
});
setState
is Asynchronous in nature. If you want to use the updated state just after setting it Callback of state is used.
Example-
setState(
{ name: "ABC" },
() => console.log(this.state)
);
// => { name: "ABC" }
Read this SO post to know when to use it.