Batching Redux Action Dispatches
Demonstrate the use of redux-batched-actions to dispatch multiple actions in a single render cycle, reducing the number of store updates and re-renders.
import { createStore, applyMiddleware } from 'redux';
import { enableBatching, batchActions } from 'redux-batched-actions';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';
// Create a store with the root reducer wrapped by enableBatching
const store = createStore(
enableBatching(rootReducer),
applyMiddleware(thunkMiddleware)
);
export default store;
This code sets up a Redux store with thunk middleware and the rootReducer. It wraps the rootReducer with enableBatching from redux-batched-actions to enable batching functionality.
import { batchActions } from 'redux-batched-actions';
import { increment, decrement } from './actionCreators';
// Batching multiple actions to be dispatched together
function batchDispatchActions() {
return (dispatch, getState) => {
dispatch(batchActions([
increment(),
decrement(),
increment(),
]));
};
}
export { batchDispatchActions };
This code demonstrates how to create a thunk action creator that batches multiple actions together using batchActions. The batchActions function takes an array of actions that will be dispatched together in a single store update.