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.