Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous nature of this.setState in React

Let's say that I have these two calls:

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

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

Because setState is asynchronous, how is it guaranteed that the first call to it will execute first?

like image 868
LearningMath Avatar asked Nov 14 '18 03:11

LearningMath


People also ask

Is setState asynchronous in React?

setState() async Issue: If you're using ReactJs, then you're likely familiar with the setState method. This function is used to update the state of a component, but it's important to remember that setState is asynchronous. This can lead to tricky debugging issues in your code.

Is setState () method synchronous or asynchronous?

setState is an Asynchronous Function.

What is asynchronous function in React?

React Async is a promise-based library that offers a declarative API to make API calls. It provides a React component and a Hook for declarative promise resolution and data fetching.

Is useState synchronous or asynchronous?

useState is an asynchronous hook, it will wait for the component to finish its cycle, re-render, and then it will update the state.


1 Answers

From the react documentation of setState() states that

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. setState() is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment or add a value to a counter more than once in the same cycle, that will result in the equivalent of:

Object.assign(
  previousState,
  {counter: previousState.counter + props.increment},
  {counter: previousState.counter + props.increment + 1},
  ...
)

Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:

this.setState((state) => {
  return {counter: state.counter + 1};
});
like image 170
SAMUEL Avatar answered Oct 18 '22 01:10

SAMUEL