React this.setState will be queued properly?

Hearen Source

As I checked the React setState

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

And this State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

What is the underlying mechanism? As I understand it, isn't it a batch update but queued following the First In First Out rule?

I am trying to make sure this FIFO rule for setState as follows:

this.setState({loading: true});
...// no matter what happened here as long as it's not stopped by errors;
this.setState({loading: false}); // the loading will always be set to **false**;

So I do not need to handle this as the following ugly way:

this.setState({loading: true}, () => {
    this.setState({loading: false});

Finally as I checked this Functional setState is the future of React, I think it indeed follows the FIFO rule.

To be super clear, passing object to setState() is not the problem here. The real problem is passing object to setState() when you want to calculate the next state from the previous state.

Hahah, Once and For ALL

Quote from Dan Abramov

It is safe to call setState with a function multiple times. Updates will be queued and later executed in the order they were called.

Please correct me if I'm wrong about this. And please share more details if it's available.

Thank you!



answered 5 days ago Shubham Khatri #1

You don't seem to dispatch the action correctly, also the promise needs to handled with dispatch and not the function like

  dispatch(askForData()).then(() => {
    this.setState({ loading: false });

comments powered by Disqus