Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs-setState previous state is the first argument, props as the second argument

Tags:

I have read in this official article these lines:

this.props and this.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

like image 586
QuickCoder Avatar asked Jun 13 '18 12:06

QuickCoder


People also ask

What is the second argument of setState in React?

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.

How do I change the previous state in React JS?

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.

How does setState work in React?

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.


1 Answers

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 })); 
like image 96
Bruno Mazzardo Avatar answered Oct 06 '22 00:10

Bruno Mazzardo