I understand from this post that React doesn't automatically batch state updates, in the case that an event is non-react
based i.e. setTimeout, Promise calls. (In short any event from Web APIs.)
This differs from react-based
events, such as those from onClick events (etc), which are batched by react to limit renders. This is well illustrated in this answer, which essentially demonstrates that while this only triggers one render:
function handleClickWithoutPromise() {
setA('aa');
setB('bb');
}
This will trigger two:
function handleClickWithPromise() {
Promise.resolve().then(() => {
setA('aa');
setB('bb');
});
}
For me this is problematic, since on my first page load I sent a request to my back-end and receive various data that is used to update numerous discrete state objects. This triggers a dozen re-renders, which is obviously not optimal.
There are some options offered on different posts, but would appreciate some expert guidance as to which is best practice:
- Redux (I haven't used this library yet and am apprehensive about overhauling my state handling). This also seems like such a common issue that I would have thought React had it's own native way of batching async state updates.
- userReducer and bundle all of my state into one. I can then update everything with one update of state. This doesn't make sense given how my different state would intuitively make more sense being kept discrete.
- Use
ReactDOM.unstable_batchedUpdates(() => { ... })
, as recommended in this answer