I'm using Redux-Toolkit v1.9.0 and React 18.2.0. I have to use dispatch
inside forEach
.
Code example
data.forEach(item => {
batch(() => store.dispatch(createTrack(item)));
})
While I was looking Redux documentation I saw an info:
If you're using React 18, you do not need to use the batch API. React 18 automatically batches all state updates, no matter where they're queued.
But when I was looking at Redux-Toolkit documentation I saw that there is a batch enhancer.
What should I do delete batch function like
data.forEach(item => {
store.dispatch(createTrack(item));
})
or change reducer?
Yes, the batch()
util exported by React-Redux was only necessary with React 17 and earlier. React 18 automatically batches all queued state updates in a single event loop tick into one re-render.
However, the autoBatchEnhancer
in RTK does something different. It cuts down on how many times the Redux store tries to notify subscribers (components) that the store state has been updated, if it sees actions marked with a "this action is low-priority" field. That's separate from React's own batching.
I wrote a post a few years ago comparing several Redux batching techniques:
And the RTK 1.9 release notes discuss the auto batch enhancer: