Opt-in to Automatic Batching with createRoot

Michael Chan
InstructorMichael Chan
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

In previous versions of React, state update batching only happened inside of event handlers. In React 18, all updates are batched, regardless of when or where they are called. Opt into automatic batching with createRoot.

Instructor: [0:00] Automatic batching of state updates is React 18's most important performance feature. To understand how it works, we need to go back to a world of React 17 using the legacy root API.

[0:14] Our app here is relatively simple. We have a count() and isOdd(). count() starts at one, and isOdd() starts with a value of true. With those, we have two state-updating functions. The app consists of a single button that calls a handleClick, onClick and renders these two pieces of state.

[0:35] The handleClick() function is where things get interesting, where we update both of these pieces of the state simultaneously. React 17 is smart enough to know that we should batch these. Every time I hit this, we only increment this console.count() one additional time, even though we're calling two state updaters.

[0:56] React 17 was only able to do this inside of the event handler callback. If the function got called later, let's say, as a result of a Fetch request, they would each increment this counter.

[1:09] Let's simulate that with setTimeout(). We can use zero seconds because the timing itself doesn't matter. Move these inside and save. Now, for each click, we see two updates. I've clicked twice. We saw a second and third for the first one and a third and fourth for the second one.

[1:30] This has been solved in React 18. If we change to the new React root API using createRoot, we see the same behavior as when the update() functions were called directly inside of the event handler. One rerender per click, this makes things consistent. No matter where these update callbacks are called, we see the same behavior.

egghead
egghead
~ 49 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today