JS Built-ins
redux-toolkitcreateListenerMiddlewareadvanced

createListenerMiddleware

πŸ“– Usage Example
const listenerMiddleware = createListenerMiddleware()
listenerMiddleware.startListening({
  actionCreator: mySlice.actions.someAction,
  effect: (action, api) => { console.log('action fired:', action.type) },
})

createListenerMiddleware provides a lightweight alternative to sagas for responding to actions with side effects.

createListenerMiddleware

Listener middleware lets you run side effects in response to dispatched actions β€” without sagas or observables.

Challenge: Set up a listener that pushes 'inc fired' to a sideEffects array every time the counter increments.

store.dispatch(counterSlice.actions.inc())
sideEffects // β†’ ['inc fired']
πŸ’‘ Hints (3)
  • β€’ Call `listenerMiddleware.startListening({ actionCreator, effect })` before creating the store.
  • β€’ Add the middleware with `middleware: m => m().concat(listenerMiddleware.middleware)`.
  • β€’ The `effect` callback runs synchronously after the action is dispatched.