0

New to react-js.

Recently, have gone through the blogs on the following case

Case 1:

state = {
count :1 
}

L1: this.setState({count:this.state.count +1});
L2: this.setState({count:this.state.count +1});
L3: ..Multiple Times..

Value of count is 2

Case 2:

state = {
count :1 
}

L4: this.setState(prevState => ({count:prevState.count+1})); 
L5: this.setState(prevState => ({count:prevState.count+1}));
L6: ..Multiple Times..

Value of count is > 3

As per the doc, calling setState multiple times will be queued for the batch update(expcetions are too there).

So as per my understanding, prevState is nothing but the prevState of the current state.

This made me to think,

Q1. If the state is not holding the updated value (case 1), then how
the prevState (case 2) will hold the updated value?

Could someone clarify here?

NANDAKUMAR THANGAVELU
  • 611
  • 3
  • 15
  • 34
  • Look at https://stackoverflow.com/questions/55495198/reacts-setstate-method-with-prevstate-argument – Mulli Apr 11 '20 at 10:06
  • Does this answer your question? [lifecycle event state and prevState in react.js](https://stackoverflow.com/questions/39806802/lifecycle-event-state-and-prevstate-in-react-js) –  Apr 11 '20 at 10:07

3 Answers3

0

When you call setState, the state is not updated until the cycled is finished. So be sure to call setState at the end of the code.

0

The function you pass to setState doesn't receive prevState in the sense of it being the previous state at the time of the batching, but rather it is guaranteed to be the most up to date version of state.

So for the first example, it's adding 1 to what state was at the time of render so no matter what, running that code will only ever add 1 to the initial value of count.

The second example shows is passing a function to set state so each call of set state there is acting upon the most recent state so it will be adding iteratively based on the previous line.

I've made a quick demo showing this: https://codesandbox.io/s/floral-haze-l1efo

Tom Finney
  • 2,670
  • 18
  • 12
0

The expression in a function argument is evaluated before the function is called and setState is asynchronous (it does not modify the state immediately, but AFTER the render).

Thus, case 1 is similar to:

this.setState({count: 2})
this.setState({count: 2})

However, in the functional form, prevState parameter is calculated fresh for each call of setState.

See also useState set method not reflecting change immediately for more complex situations.

Aprillion
  • 21,510
  • 5
  • 55
  • 89