0

I was reading the page on React's docs about State and Lifecycle:

https://reactjs.org/docs/state-and-lifecycle.html

And I don't understand why you can pass a function to "setState" to make state updates synchronous.

In other words, according to the docs:

this.setState({ counter: this.state.counter + this.props.increment, });

Might update the counter when it's executed... or it might not. But this:

this.setState((state, props) => ({ counter: state.counter + props.increment }));

Will always update the counter.

Why? What's the difference between both? What does React do internally in that case? Does it execute the internal function first and then store the result to update the state later, when it's better for performance? Or does it update the state inmediately? And in that case, is that a good practice for performance? Or does it do something completely different?

PaulJ
  • 1,646
  • 5
  • 33
  • 52
  • 3
    The second form helps to ensure you have the current values of state/props at the time of the update if you are using those values to calculate the next state. It is not synchronous, it is still asynchronous. Try putting a `console.log` right after `setState` to see that. – Alexander Staroselsky Jul 24 '20 at 16:27
  • 1
    Because, as that page says, "this.props and this.state may be updated asynchronously," But, inside the function, they are frozen in time, at the time of the function call, to their current values, then set to State. This forces `setState` to act as if all were synchronous. – GAEfan Jul 24 '20 at 16:33

0 Answers0