Search code examples
reactjsreduxredux-toolkitreact-18

React-redux batch on React v.18


im 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 documantation 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 reduxtoolkit documantation i saw that there is a batch enchanter.

What should i do delete batch function like

   data.forEach(item => {
    store.dispatch(createTrack(item));
    })

or change reducer ?


Solution

  • 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: