JimmyTheCode
JimmyTheCode

Reputation: 5694

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 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:

Upvotes: 5

Views: 3806

Answers (1)

JimmyTheCode
JimmyTheCode

Reputation: 5694

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.

Upvotes: 4

Related Questions