It is ok if this is your first time to read about it, because it is one of the not documented APIs in React, Yes you can not find it in the react's official documentation, although it is a part of the library.
First we need to know What is batching state update?
According to Dan Abramov -co-authored the Create React App
Batching is when React groups multiple state updates into a single re-render for better performance.
function App() {
const [count, setCount] = useState(0);
const [isEven, setIsEven] = useState(false);
function handleClick() {
setCount(c => c + 1); // Does not re-render yet
setIsEven(f => !f); // Does not re-render yet
// React will only re-render once at the end (that's batching!)
}
return (
<div>
<button onClick={handleClick}>counter{count}</button>
</div>
);
}
In earlier React versions (17 and earlier) there was batching only in browser event (like click), and it wasn't available in
- Native DOM event listeners (e.g., el.addEventListener())
- Async callbacks (e.g., promises, timeouts, intervals)
and to make it available you had to use unstable_batchedUpdates
to enforce batching
How to use it unstable_batchedUpdates
?
import {unstable_batchedUpdates} from 'react-dom';
const batchUpdate = unstable_batchedUpdates(() => {
setName('Moustafa');
setAge(25);
});
batchUpdate() //this will group all state changes inside and apply it in one re-render
Good News
if you're using React 18 and above, you do not need it anymore because React 18 now support automatic batching.
This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events
you can read more about it here
Warning ⚠️
Since React 18 now supports automatic batching and it is
a not documented API and it might get removed in a future major version of React after popular libraries no longer depend on its existence.
Top comments (0)