Sub topic 14
Middleware and the listener middleware
This chapter assumes you can build a slice and configure a store with configureStore, and that you know how thunks work from the async chapter. It covers what middleware is, which middleware RTK installs by default, how to write your own, and how the listener middleware runs side effects in response to actions.
What middleware is
Middleware is a function that sits between dispatch(action) and the reducer. Every action passes through the middleware chain before it reaches the reducers. A middleware can inspect the action, change it, delay it, dispatch other actions, or stop it from going any further.
Every middleware has the same three-level shape:
export const actionLogger = (storeApi) => (next) => (action) => {
console.log('dispatching', action.type)
const result = next(action)
console.log('state after', storeApi.getState())
return result
}storeApihasdispatchandgetState.nextpasses the action to the next middleware. The lastnextis the real reducer call.actionis whatever was dispatched.
Code before next(action) runs before the reducers. Code after it runs once the reducers have produced the new state. If you never call next, the action stops there. This is how redux-thunk works: when it sees a function instead of an action object, it calls the function and does not pass it on.
Default middleware in configureStore
configureStore builds a default middleware array. The contents depend on the environment:
| Middleware | Runs in | Purpose |
|---|---|---|
| Thunk | Always | Lets you dispatch functions, which `createAsyncThunk` relies on |
| Immutability check | Development | Throws if state is mutated outside a reducer |
| Serializability check | Development | Warns about non-serializable values in actions or state |
| Action creator check | Development | Warns if you pass an action creator, such as `incremented`, to `dispatch` without calling it |
To add your own middleware, use a callback and concat or prepend:
import { configureStore } from '@reduxjs/toolkit'
import { actionLogger } from './actionLogger'
import counterReducer from './counterSlice'
export const store = configureStore({
reducer: { counter: counterReducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(actionLogger),
})Do not pass a plain array such as middleware: [actionLogger]. That replaces the defaults, and you lose thunk, so createAsyncThunk stops working.
Order matters. The first middleware in the array sees the action first and sees the result last. concat adds to the end of the chain. prepend adds to the start.
Why a listener middleware
Sometimes you need code that says "when action X happens, do Y". Typical cases:
- Save part of the state to
localStoragewhen it changes. - Debounce a search box.
- Start a request after a user logs in.
- Wait for one of several actions, then continue.
You could write a custom middleware with an if (action.type === ...) check for each of these. You could also put the logic inside thunks. A custom middleware gets crowded quickly, and a thunk only runs when you dispatch it by hand. The listener middleware gives you declarative "on this action, run this effect" rules, with helpers for cancelling, delaying and waiting.
Setting up the listener middleware
Create one listener middleware instance and register listeners with startListening:
import {
configureStore,
createListenerMiddleware,
createSlice,
} from '@reduxjs/toolkit'
const todosSlice = createSlice({
name: 'todos',
initialState: { items: [] },
reducers: {
todoAdded(state, action) {
state.items.push(action.payload)
},
},
})
export const { todoAdded } = todosSlice.actions
export const listenerMiddleware = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: todoAdded,
effect: (action, listenerApi) => {
const { items } = listenerApi.getState().todos
localStorage.setItem('todos', JSON.stringify(items))
},
})
export const store = configureStore({
reducer: { todos: todosSlice.reducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})Each listener has a trigger and an effect. The trigger can be one of these:
actionCreator: matches one action, for exampletodoAdded.type: matches an action type string.matcher: matches with an RTK matcher such asisAnyOf(a, b).predicate: a function(action, currentState, previousState) => booleanfor conditions that depend on state changes.
The effect receives the action and a listenerApi object. The effect runs after the reducers have processed the action, so getState() already includes the update. If you need the state from before the action, use the getOriginalState() method.
The docs recommend prepend for the listener middleware. That way it sees every action before another middleware can swallow it.
The listenerApi toolbox
Effects can be async. These listenerApi methods cover the usual patterns:
| Method | What it does |
|---|---|
| `getState()` | Returns the current state |
| `getOriginalState()` | Returns the state before this action. Only valid during the synchronous part of the effect |
| `dispatch(action)` | Dispatches another action |
| `delay(ms)` | Waits, and throws if the effect is cancelled meanwhile |
| `condition(predicate, timeout?)` | Waits until a matching action arrives. Resolves to `true`, or to `false` if the timeout passes first |
| `take(predicate, timeout?)` | Like `condition`, but resolves with the matching action and state, or `null` on timeout |
| `cancelActiveListeners()` | Cancels earlier running runs of the same listener |
| `fork(fn)` | Starts a child task you can await or cancel |
| `unsubscribe()` | Removes this listener |
Example: debouncing a search
This is a classic job for cancelActiveListeners and delay:
import {
configureStore,
createAction,
createListenerMiddleware,
createSlice,
} from '@reduxjs/toolkit'
const searchSubmitted = createAction('search/submitted')
const searchSlice = createSlice({
name: 'search',
initialState: { text: '', submitted: '' },
reducers: {
searchChanged(state, action) {
state.text = action.payload
},
},
extraReducers: (builder) => {
builder.addCase(searchSubmitted, (state, action) => {
state.submitted = action.payload
})
},
})
const { searchChanged } = searchSlice.actions
const listenerMiddleware = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: searchChanged,
effect: async (action, listenerApi) => {
listenerApi.cancelActiveListeners()
await listenerApi.delay(300)
listenerApi.dispatch(searchSubmitted(action.payload))
},
})
const store = configureStore({
reducer: { search: searchSlice.reducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})
store.dispatch(searchChanged('re'))
store.dispatch(searchChanged('redux'))
setTimeout(() => {
console.log(store.getState().search.submitted)
}, 400)Each searchChanged cancels the effect run that is still waiting. When delay is cancelled it throws an internal TaskAbortError, which the middleware ignores. Only the last keystroke reaches searchSubmitted, so the program prints redux.
Common errors
- Using an array for
middleware. This drops the defaults, including thunk. Always use the callback form. - Forgetting to add the middleware.
createListenerMiddleware()alone does nothing. You must putlistenerMiddleware.middlewarein the store. - Registering listeners that are never imported.
startListeninghas to run before the action you care about. If a listener lives in a file nothing imports, it never runs. - Reading state from before the action.
getState()returns the state after the reducers ran. UsegetOriginalState()for the old state, and call it before anyawait. - Infinite loops. If an effect dispatches the same action that triggers it, it triggers itself again. Dispatch a different action, or add a guard.
- Errors in effects. An error thrown in an effect does not crash the dispatch. The middleware reports it to the
onErroroption, which logs to the console by default. SetonErrorincreateListenerMiddleware({ onError })if you want to report errors somewhere else.
Choosing between the tools
| Need | Best fit |
|---|---|
| Run a request when a component asks for it | `createAsyncThunk` |
| Fetch and cache server data | RTK Query |
| React to an action after it is processed, or debounce or cancel work | Listener middleware |
| Change, delay or block actions before the reducer, or log every action | Custom middleware |
Many apps need no custom middleware at all. Start with thunks and RTK Query, and add listeners when you find yourself wanting "when X happens, do Y".
Exercise
A teammate writes middleware: [actionLogger] in configureStore and then finds that createAsyncThunk actions no longer work. Why does this happen, and what is the fix?
Show answer
Passing an array replaces the default middleware, so the thunk middleware is gone and dispatched thunk functions are never run. The fix is the callback form: middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(actionLogger).
Exercise
You want a listener that runs when either userLoggedIn or tokenRefreshed is dispatched. Which trigger option fits, and how do you write it?
Show answer
Use matcher with isAnyOf: listenerMiddleware.startListening({ matcher: isAnyOf(userLoggedIn, tokenRefreshed), effect: (action, listenerApi) => { /* ... */ } }). isAnyOf is exported from @reduxjs/toolkit.