sajad torkamani

In React 18, all state updates are batched by default. Usually, this is what you want, but in the rare case that you need to read from the DOM immediately after a state change, you can use ReactDOM.flushSync() to opt out of batching.

import { flushSync } from 'react-dom'

function handleClick() {
  flushSync(() => {
    setCounter(c => c + 1)
  })
  // React has updated the DOM by now
  flushSync(() => {
    setFlag(f => !f)
  })
  // React has updated the DOM by now
}

Sources

Tagged: React

Leave a comment

Your email address will not be published. Required fields are marked *