Code splitting
A feature is loaded lazily and needs middleware only when that feature becomes active.
Redux Toolkit · Function
Creates a meta-middleware instance that lets applications add middleware to a Redux dispatch chain after store initialization. Register its middleware wrapper during store setup, then inject middleware through the instance.
createDynamicMiddleware returns an instance containing a wrapper middleware and methods for adding middleware after the store exists. Put the wrapper in the store's middleware chain, then use addMiddleware or the withMiddleware action to inject middleware; injected middleware stays within the wrapper's position.
createDynamicMiddleware<State, Dispatch>()Returns a dynamic middleware instance containing the middleware wrapper and methods for injecting middleware.
import { configureStore, createDynamicMiddleware } from '@reduxjs/toolkit'
import logger from 'redux-logger'
const dynamicMiddleware = createDynamicMiddleware()
const store = configureStore({
reducer: (state = {}) => state,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(dynamicMiddleware.middleware),
})
dynamicMiddleware.addMiddleware(logger)
store.dispatch({ type: 'demo' })Register the wrapper when creating the store, then add a middleware later at runtime.
A feature is loaded lazily and needs middleware only when that feature becomes active.
Middleware such as logging or monitoring must be enabled after the store has been created.
A React application needs dispatch types that include extensions supplied by injected middleware.
It is a meta-middleware that lets the dispatch chain receive middleware after store initialization. Add its middleware property to configureStore, then inject middleware through the returned instance.
Follow-up: Where does injected middleware run? It runs inside the wrapper's position in the store middleware chain.
addMiddleware accepts middleware and immediately injects it into the dynamic instance. withMiddleware instead creates an action; dispatching that action injects the middleware and returns dispatch typed for the added extensions.
Follow-up: Why might withMiddleware be preferable in TypeScript? It can return dispatch with the newly added middleware extensions represented in its type.
The returned instance can receive State and Dispatch type parameters. Those types are used to check that middleware supplied to its methods is compatible with the declared state and dispatch types.
Follow-up: What React-specific integration is available? The React entry point adds a hook that returns useDispatch typed with extensions from supplied middleware, provided react-redux is installed.
configureStorecreateListenerMiddlewareaddMiddlewarewithMiddlewarecreateDispatchWithMiddlewareHook