How it works...

Why did we need to pass a function? There's a key point to understanding this: state updates are asynchronous. Whenever you call .setState(), React will update the component's state and start its reconciliation process to update the UI view. But what happens if there is more than one .setState() call? There lies the problem.

React is allowed to queue many such calls together into a single update to achieve better performance, and that has an important effect: state may have changed before .setState() is executed! (Even so, if batching is done, updates will be done in the order they are called.) So, you provide a function and React will call it with the appropriately updated state parameter. Don't do anything depending on this.state because it may be wrong; always work with the state parameter.

There is a shortcut that you should know, in any case. If (and only if) your update does not depend in any way on the state or props values, you can use an alternative call without requiring a function. For example, our update could have been simply written as follows, and this.state.regions would be changed, leaving the rest of the state unchanged; the key is that the new values for the regions attribute are not dependent in any way on state or props:

this.setState({ regions: [ ... ]});

Why would this work? Because in this case, even if the state had changed before, your update would still be the same. Be careful, though, and use this syntax only when your update is totally independent of state and props; otherwise, use the functional approach we showed first.

Once you realize that the state updates are functions, you can move that logic out of components, for separate, independent coding and testing, this will be quite similar to things we'll be doing with Redux in Chapter 8, Expanding your Application. You would write this.setState(someFunction) and someFunction() would be defined separately; your code will have become more declarative in style.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.144.228