|
| 1 | +--- |
| 2 | +id: autoBatchEnhancer |
| 3 | +title: autoBatchEnhancer |
| 4 | +sidebar_label: autoBatchEnhancer |
| 5 | +hide_title: true |
| 6 | +--- |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +# `autoBatchEnhancer` |
| 11 | + |
| 12 | +A Redux store enhancer that looks for one or more "low-priority" dispatched actions in a row, and queues a callback to run subscriber notifications on a delay. It then notifies subscribers either when the queued callback runs, or when the next "normal-priority" action is dispatched, whichever is first. |
| 13 | + |
| 14 | +## Basic Usage |
| 15 | + |
| 16 | +```ts |
| 17 | +import { |
| 18 | + createSlice, |
| 19 | + configureStore, |
| 20 | + autoBatchEnhancer, |
| 21 | + prepareAutoBatched, |
| 22 | +} from '@reduxjs/toolkit' |
| 23 | + |
| 24 | +interface CounterState { |
| 25 | + value: number |
| 26 | +} |
| 27 | + |
| 28 | +const counterSlice = createSlice({ |
| 29 | + name: 'counter', |
| 30 | + initialState: { value: 0 } as CounterState, |
| 31 | + reducers: { |
| 32 | + incrementBatched: { |
| 33 | + // Batched, low-priority |
| 34 | + reducer(state) { |
| 35 | + state.value += 1 |
| 36 | + }, |
| 37 | + // highlight-start |
| 38 | + // Use the `prepareAutoBatched` utility to automatically |
| 39 | + // add the `action.meta[SHOULD_AUTOBATCH]` field the enhancer needs |
| 40 | + prepare: prepareAutoBatched<void>(), |
| 41 | + // highlight-end |
| 42 | + }, |
| 43 | + // Not batched, normal priority |
| 44 | + decrementUnbatched(state) { |
| 45 | + state.value -= 1 |
| 46 | + }, |
| 47 | + }, |
| 48 | +}) |
| 49 | +const { incrementBatched, decrementUnbatched } = counterSlice.actions |
| 50 | + |
| 51 | +const store = configureStore({ |
| 52 | + reducer: counterSlice.reducer, |
| 53 | + // highlight-start |
| 54 | + enhancers: (existingEnhancers) => { |
| 55 | + // Add the autobatch enhancer to the store setup |
| 56 | + return existingEnhancers.concat(autoBatchEnhancer()) |
| 57 | + }, |
| 58 | + // highlight-end |
| 59 | +}) |
| 60 | +``` |
| 61 | + |
| 62 | +## API |
| 63 | + |
| 64 | +### `autoBatchEnhancer` |
| 65 | + |
| 66 | +```ts title="autoBatchEnhancer signature" no-transpile |
| 67 | +export type SHOULD_AUTOBATCH = string |
| 68 | +type AutoBatchOptions = |
| 69 | + | { type: 'tick' } |
| 70 | + | { type: 'timer'; timeout: number } |
| 71 | + | { type: 'raf' } |
| 72 | + | { type: 'callback'; queueNotification: (notify: () => void) => void } |
| 73 | + |
| 74 | +export type autoBatchEnhancer = (options?: AutoBatchOptions) => StoreEnhancer |
| 75 | +``` |
| 76 | +
|
| 77 | +Creates a new instance of the autobatch store enhancer. |
| 78 | +
|
| 79 | +Any action that is tagged with `action.meta[SHOULD_AUTOBATCH] = true` will be treated as "low-priority", and a notification callback will be queued. The enhancer will delay notifying subscribers until either: |
| 80 | +
|
| 81 | +- The queued callback runs and triggers the notifications |
| 82 | +- A "normal-priority" action (any action _without_ `action.meta[SHOULD_AUTOBATCH] = true`) is dispatched in the same tick |
| 83 | +
|
| 84 | +`autoBatchEnhancer` accepts options to configure how the notification callback is queued: |
| 85 | +
|
| 86 | +- `{type: 'raf'}`: queues using `requestAnimationFrame` (default) |
| 87 | +- `{type: 'tick'}: queues using `queueMicrotask` |
| 88 | +- `{type: 'timer, timeout: number}`: queues using `setTimeout` |
| 89 | +- `{type: 'callback', queueNotification: (notify: () => void) => void}: lets you provide your own callback, such as a debounced or throttled function |
| 90 | +
|
| 91 | +The default behavior is to queue the notifications using `requestAnimationFrame`. |
| 92 | +
|
| 93 | +The `SHOULD_AUTOBATCH` value is meant to be opaque - it's currently a string for simplicity, but could be a `Symbol` in the future. |
| 94 | +
|
| 95 | +### `prepareAutoBatched` |
| 96 | +
|
| 97 | +```ts title="prepareAutoBatched signature" no-transpile |
| 98 | +type prepareAutoBatched = <T>() => (payload: T) => { payload: T; meta: unknown } |
| 99 | +``` |
| 100 | +
|
| 101 | +Creates a function that accepts a `payload` value, and returns an object with `{payload, meta: {[SHOULD_AUTOBATCH]: true}}`. This is meant to be used with RTK's `createSlice` and its "`prepare` callback" syntax: |
| 102 | +
|
| 103 | +```ts no-transpile |
| 104 | +createSlice({ |
| 105 | + name: 'todos', |
| 106 | + initialState, |
| 107 | + reducers: { |
| 108 | + todoAdded: { |
| 109 | + reducer(state, action: PayloadAction<Todo>) { |
| 110 | + state.push(action.payload) |
| 111 | + }, |
| 112 | + // highlight-start |
| 113 | + prepare: prepareAutoBatched<Todo>(), |
| 114 | + // highlight-end |
| 115 | + }, |
| 116 | + }, |
| 117 | +}) |
| 118 | +``` |
| 119 | +
|
| 120 | +## Batching Approach and Background |
| 121 | +
|
| 122 | +The post [A Comparison of Redux Batching Techniques](https://blog.isquaredsoftware.com/2020/01/blogged-answers-redux-batching-techniques/) describes four different approaches for "batching Redux actions/dispatches" |
| 123 | +
|
| 124 | +- a higher-order reducer that accepts multiple actions nested inside one real action, and iterates over them together |
| 125 | +- an enhancer that wraps `dispatch` and debounces the notification callback |
| 126 | +- an enhancer that wraps `dispatch` to accept an array of actions |
| 127 | +- React's `unstable_batchedUpdates()`, which just combines multiple queued renders into one but doesn't affect subscriber notifications |
| 128 | +
|
| 129 | +This enhancer is a variation of the "debounce" approach, but with a twist. |
| 130 | +
|
| 131 | +Instead of _just_ debouncing _all_ subscriber notifications, it watches for any actions with a specific `action.meta[SHOULD_AUTOBATCH]: true` field attached. |
| 132 | +
|
| 133 | +When it sees an action with that field, it queues a callback. The reducer is updated immediately, but the enhancer does _not_ notify subscribers right way. If other actions with the same field are dispatched in succession, the enhancer will continue to _not_ notify subscribers. Then, when the queued callback runs, it finally notifies all subscribers, similar to how React batches re-renders. |
| 134 | +
|
| 135 | +The additional twist is also inspired by React's separation of updates into "low-priority" and "immediate" behavior (such as a render queued by an AJAX request vs a render queued by a user input that should be handled synchronously). |
| 136 | +
|
| 137 | +If some low-pri actions have been dispatched and a notification microtask is queued, then a _normal_ priority action (without the field) is dispatched, the enhancer will go ahead and notify all subscribers synchronously as usual, and _not_ notify them at the end of the tick. |
| 138 | +
|
| 139 | +This allows Redux users to selectively tag certain actions for effective batching behavior, making this purely opt-in on a per-action basis, while retaining normal notification behavior for all other actions. |
| 140 | +
|
| 141 | +### RTK Query and Batching |
| 142 | +
|
| 143 | +RTK Query already marks several of its key internal action types as batchable. If you add the `autoBatchEnhancer` to the store setup, it will improve the overall UI performance, especially when rendering large lists of components that use the RTKQ query hooks. |
0 commit comments