Opt-out of Automatic Batching with ReactDOM.flushSync

Michael Chan
InstructorMichael Chan
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

In React 18, useState update calls are batched for improved performance. A new API — ReactDOM.flushSync — lets us selectively escape batching. This option is useful when reading the DOM after state changes. Use ReactDOM.flushSync to exempt specific state updates from batching.

Instructor: [0:00] ReactDOM 18 provides a way to opt out of automatic batching of state updates. Because of automatic batching, these two state updates always happen in the same rerender. We can split them using ReactDOM flushSync, simply wrap the update in ReactDOM.flushSync.

[0:26] With this, we're separating these updates by forcing this one to flush to the DOM first. Now, every time we click our button, we see two individual updates. We can repeat this process for as many state updates as we like.