简体   繁体   中英

What's the best way to batch state updates from async calls in React?

I understand from this post that React doesn't automatically batch state updates, in the case that an event is non-react based ie 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

So, just in case no better answers are forthcoming, I found this article on Medium that shows a really good, simple example of the ReactDOM.unstable_batchedUpdates(() => {... }) working. (You have to scroll a way down to the section: "How to force batching?" ).

The author also adds that:

Although this function is supposedly “unstable”, React apparently intends to address this in the following versions.

“In future versions (probably React 17 and later), React will batch all updates by default so you won't have to think about this” , according to Dan Abramov.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM