Middle
In a functional React component, there are two synchronous setState calls, then an asynchronous function, then three more setState calls. How many renders will occur in React 18 and React 17? What is batching and when did it appear?
sobes.tech AI
Answer from AI
In React 17 and earlier versions, batching (batch processing of state updates) occurred only inside React event handlers. This means that multiple calls to setState within a single handler were combined into one render.
If a functional component has two setState calls in a row, then an asynchronous function, then three more setState calls, then:
-
In React 17:
- The first two
setStatecalls in a synchronous block will be combined into one render. - The asynchronous function (e.g.,
setTimeoutor a promise) will break batching, so the following threesetStatecalls will be processed separately, each potentially causing a separate render if not combined manually. - Total: at least 4 renders (1 after the first two calls, and up to 3 after each of the three calls following the asynchronous code).
- The first two
-
In React 18:
- Extended automatic batching was introduced, which combines all
setStatecalls, including asynchronous ones (e.g., inside promises, timeouts, etc.). - All 5
setStatecalls (2 before the asynchronous function and 3 after) will be combined into one render. - Total: 1 render.
- Extended automatic batching was introduced, which combines all
What is batching? Batching is a mechanism that combines multiple state updates into one render to improve performance and avoid unnecessary re-renders.
When did extended batching appear? Extended automatic batching was introduced in React 18, significantly improving performance when working with asynchronous code.