Reduce repeated subscriber work
Several state updates are dispatched together and subscriber work, such as UI rendering, should be deferred.
Redux Toolkit · Function
autoBatchEnhancer delays subscriber notifications while consecutive low-priority actions are dispatched. It flushes on its scheduled callback or when a normal-priority action arrives in the same tick.
autoBatchEnhancer delays subscriber notifications for consecutive low-priority actions. It flushes when its queued callback runs or when a normal-priority action is dispatched in the same tick.
autoBatchEnhancer(options?: AutoBatchOptions)| Name | Type | Description |
|---|---|---|
options | AutoBatchOptions | Optional configuration selecting raf, tick, timer, or callback notification scheduling. |
A Redux store enhancer that delays subscriber notifications for tagged low-priority actions.
import { configureStore, createSlice } from '@reduxjs/toolkit'
const slice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1 },
},
})
const store = configureStore({
reducer: slice.reducer,
enhancers: (getDefaultEnhancers) =>
getDefaultEnhancers({ autoBatch: { type: 'tick' } }),
})
store.dispatch({
type: 'counter/increment',
meta: { RTK_autoBatch: true },
})Configures the default enhancer with microtask-based notification scheduling and dispatches a low-priority action.
Several state updates are dispatched together and subscriber work, such as UI rendering, should be deferred.
The default requestAnimationFrame timing is unsuitable for a particular environment or latency requirement.
A project needs application-specific debouncing or throttling of subscriber notifications.
It is a store enhancer that recognizes consecutive low-priority actions and postpones subscriber notifications. Notifications occur when the scheduled callback executes or when a normal-priority action arrives in the same tick.
Follow-up: How can its scheduling policy be changed? Pass an options object selecting raf, tick, timer, or callback behavior through configureStore's enhancer customization.
RTK 2.0 includes it in configureStore by default. To change its behavior, provide an enhancers callback and customize the autoBatch option returned by getDefaultEnhancers.
Follow-up: How would you preserve the other default enhancers? Return getDefaultEnhancers with the autoBatch options rather than replacing the enhancer list outright.
The default queue uses requestAnimationFrame. The tick option uses queueMicrotask, timer uses setTimeout, and callback lets the application supply its own notification scheduler.
Follow-up: When would a custom callback be useful? It can implement application-specific debouncing or throttling around subscriber notification.
configureStoregetDefaultEnhancersprepare callbackSHOULD_AUTOBATCH