I have read in this official article these lines:
this.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
Can anyone please explain to me what the following code is trying to achieve by giving an example.
this.setState((prevState, props) => ({ couter: prevState.counter + props.increment }));
I am referring to this official website of reactjs React.js
The second argument that can optionally be passed to setState is a callback function which gets called immediately after the setState is completed and the components get re-rendered.
state , we use this. setState() . This is a function available to all React components that use state, and allows us to let React know that the component state has changed. This way the component knows it should re-render, because its state has changed and its UI will most likely also change.
It ensures that the component has been updated and calls for re-rendering of the component. setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console.
They say you should do like that instead of the below example.
// Wrong this.setState({ counter: this.state.counter + this.props.increment, });
They can't assure the state will have the correct value if you access like this because setState() will happen asynchronously, other updates could occur and change the value. If you are going to calculate the state based on the previous state, you have to make sure you have the last and most up to date value, so they made setState() accept a function that is called with prevState and props, so you can have the correct value to update your state, like the example below.
// Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With