Redux Listener Middleware
React to dispatched actions and state changes with createListenerMiddleware for structured side effects
When to Use
- Running side effects in response to specific actions (analytics, logging, sync)
- Implementing "when X happens, do Y" reactive logic that does not fit in a reducer
- Replacing redux-saga or redux-observable with a simpler built-in alternative
- Coordinating cross-slice logic (when slice A changes, update slice B)
Instructions
- Create the listener middleware once with
createListenerMiddleware(). Add it to the store via the middleware callback.
- Use
startListening to register listeners. Match actions with actionCreator, type, matcher, or predicate.
- The
effect callback receives the matched action and a listenerApi with dispatch, getState, getOriginalState, condition, take, delay, and more.
- Use
listenerApi.condition() to wait for a future state condition before continuing. Use listenerApi.take() to wait for a specific action.
- Use
listenerApi.cancelActiveListeners() at the start of the effect to debounce — cancels previous runs of the same listener.
- Return or call
listenerApi.unsubscribe() to remove the listener dynamically.
// store/listenerMiddleware.ts
import { createListenerMiddleware, isAnyOf } from '@reduxjs/toolkit';
import { addTodo, toggleTodo } from '../features/todos/todos.slice';
import { RootState } from './index';
export const listenerMiddleware = createListenerMiddleware();
// Sync todos to localStorage whenever they change
listenerMiddleware.startListening({
matcher: isAnyOf(addTodo, toggleTodo),
effect: async (action, listenerApi) => {
const state = listenerApi.getState() as RootState;
localStorage.setItem('todos', JSON.stringify(state.todos.items));
},
});
// Debounced search — cancel previous runs
listenerMiddleware.startListening({
actionCreator: setSearchQuery,
effect: async (action, listenerApi) => {
// Cancel any in-progress instances of this listener
listenerApi.cancelActiveListeners();
// Debounce 300ms
await listenerApi.delay(300);
// If we get here, no new setSearchQuery was dispatched
listenerApi.dispatch(fetchSearchResults(action.payload));
},
});
// store/index.ts
import { listenerMiddleware } from './listenerMiddleware';
export const store = configureStore({
reducer: {
/* ... */
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
});
Details
Matching strategies:
actionCreator — exact action creator match (best TypeScript inference)
type — string match on action.type
matcher — any RTK matcher (isAnyOf, isAllOf, isRejected)
predicate — (action, currentState, previousState) => boolean for state-based conditions
condition and take: These let you write multi-step async workflows:
listenerMiddleware.startListening({
actionCreator: startCheckout,
effect: async (action, listenerApi) => {
// Wait for payment to complete (or timeout after 60s)
const [paymentAction] = await listenerApi.take(paymentCompleted.match, 60_000);
if (paymentAction) {
listenerApi.dispatch(finalizeOrder());
} else {
listenerApi.dispatch(checkoutTimedOut());
}
},
});
Comparison with alternatives:
- Thunks: Best for single async operations dispatched from components. Listeners are best for reactive "when X happens do Y" patterns.
- Sagas: Listeners cover most saga use cases without generators. Use sagas only if you need advanced concurrency patterns (races, forks, channels).
- Observables: Listeners handle serial async workflows well. Use RxJS only if you need complex stream composition.
Prepend, not concat: Use .prepend(listenerMiddleware.middleware) so listeners run before other middleware.
Source
https://redux-toolkit.js.org/api/createListenerMiddleware
Process
- Read the instructions and examples in this document.
- Apply the patterns to your implementation, adapting to your specific context.
- Verify your implementation against the details and edge cases listed above.
Harness Integration
- Type: knowledge — this skill is a reference document, not a procedural workflow.
- No tools or state — consumed as context by other skills and agents.
Success Criteria
- The patterns described in this document are applied correctly in the implementation.
- Edge cases and anti-patterns listed in this document are avoided.
1---2name: redux-listener-middleware3description: Redux Listener Middleware4metadata:5 source: https://skillmd.com/skills/intense-visions/redux-listener-middleware6---7# Redux Listener Middleware89> React to dispatched actions and state changes with createListenerMiddleware for structured side effects1011## When to Use1213- Running side effects in response to specific actions (analytics, logging, sync)14- Implementing "when X happens, do Y" reactive logic that does not fit in a reducer15- Replacing redux-saga or redux-observable with a simpler built-in alternative16- Coordinating cross-slice logic (when slice A changes, update slice B)1718## Instructions19201. Create the listener middleware once with `createListenerMiddleware()`. Add it to the store via the `middleware` callback.212. Use `startListening` to register listeners. Match actions with `actionCreator`, `type`, `matcher`, or `predicate`.223. The `effect` callback receives the matched `action` and a `listenerApi` with `dispatch`, `getState`, `getOriginalState`, `condition`, `take`, `delay`, and more.234. Use `listenerApi.condition()` to wait for a future state condition before continuing. Use `listenerApi.take()` to wait for a specific action.245. Use `listenerApi.cancelActiveListeners()` at the start of the effect to debounce — cancels previous runs of the same listener.256. Return or call `listenerApi.unsubscribe()` to remove the listener dynamically.2627```typescript28// store/listenerMiddleware.ts29import { createListenerMiddleware, isAnyOf } from '@reduxjs/toolkit';30import { addTodo, toggleTodo } from '../features/todos/todos.slice';31import { RootState } from './index';3233export const listenerMiddleware = createListenerMiddleware();3435// Sync todos to localStorage whenever they change36listenerMiddleware.startListening({37 matcher: isAnyOf(addTodo, toggleTodo),38 effect: async (action, listenerApi) => {39 const state = listenerApi.getState() as RootState;40 localStorage.setItem('todos', JSON.stringify(state.todos.items));41 },42});4344// Debounced search — cancel previous runs45listenerMiddleware.startListening({46 actionCreator: setSearchQuery,47 effect: async (action, listenerApi) => {48 // Cancel any in-progress instances of this listener49 listenerApi.cancelActiveListeners();50 // Debounce 300ms51 await listenerApi.delay(300);52 // If we get here, no new setSearchQuery was dispatched53 listenerApi.dispatch(fetchSearchResults(action.payload));54 },55});56```5758```typescript59// store/index.ts60import { listenerMiddleware } from './listenerMiddleware';6162export const store = configureStore({63 reducer: {64 /* ... */65 },66 middleware: (getDefaultMiddleware) =>67 getDefaultMiddleware().prepend(listenerMiddleware.middleware),68});69```7071## Details7273**Matching strategies:**7475- `actionCreator` — exact action creator match (best TypeScript inference)76- `type` — string match on `action.type`77- `matcher` — any RTK matcher (`isAnyOf`, `isAllOf`, `isRejected`)78- `predicate` — `(action, currentState, previousState) => boolean` for state-based conditions7980**condition and take:** These let you write multi-step async workflows:8182```typescript83listenerMiddleware.startListening({84 actionCreator: startCheckout,85 effect: async (action, listenerApi) => {86 // Wait for payment to complete (or timeout after 60s)87 const [paymentAction] = await listenerApi.take(paymentCompleted.match, 60_000);88 if (paymentAction) {89 listenerApi.dispatch(finalizeOrder());90 } else {91 listenerApi.dispatch(checkoutTimedOut());92 }93 },94});95```9697**Comparison with alternatives:**9899- **Thunks:** Best for single async operations dispatched from components. Listeners are best for reactive "when X happens do Y" patterns.100- **Sagas:** Listeners cover most saga use cases without generators. Use sagas only if you need advanced concurrency patterns (races, forks, channels).101- **Observables:** Listeners handle serial async workflows well. Use RxJS only if you need complex stream composition.102103**Prepend, not concat:** Use `.prepend(listenerMiddleware.middleware)` so listeners run before other middleware.104105## Source106107https://redux-toolkit.js.org/api/createListenerMiddleware108109## Process1101111. Read the instructions and examples in this document.1122. Apply the patterns to your implementation, adapting to your specific context.1133. Verify your implementation against the details and edge cases listed above.114115## Harness Integration116117- **Type:** knowledge — this skill is a reference document, not a procedural workflow.118- **No tools or state** — consumed as context by other skills and agents.119120## Success Criteria121122- The patterns described in this document are applied correctly in the implementation.123- Edge cases and anti-patterns listed in this document are avoided.