If I have different setState()
calls does their order matter while executing them?
Basically, yes, it does. They are processed in the order in which they are queued up (and batched) during each render cycle.
Will setState()
[2] wait until setstate()
[1] has finished?
No, all state updates are batched and process during react's reconciliation cycle.
- In the case where each state update is independent, then the order in which they process doesn't really matter.
- Sometimes, however, state updates depend on the previous state
value, (i.e. incrementing counters); these are where you want to use
functional state updates so if more than one update is queued then
each subsequent update uses the result of the previous update.
- In
some other cases though, one state value may depend on another, different, state value.
Here's a codesandbox demo I use to help illustrate the second case.
For the third case there are a couple options. First is the class-based component's setState
callback (functional components' useState
hook does not have this), which is guaranteed to run after the state is updated. This, however, can lead to nesting issues. The second, and IMO, more correct way, is to use the component lifecycle functions (or hooks in functional components) to responded to specific state values updating and triggering other state updates to other state values.