Sub topic 14
Middleware and the listener middleware
This chapter assumes you can write a slice, configure a store with configureStore, and dispatch actions from React components. It also assumes you know how createAsyncThunk works. Here you will learn where middleware sits in the Redux data flow, what configureStore adds by default, and how to run side effects with the listener middleware.
What middleware is
Middleware is a function that sits between dispatch and the reducer. Every action passes through it before the reducer sees it. Middleware can log the action, delay it, change it, or dispatch more actions.
Reducers must be pure, so they cannot make network calls or set timers. Middleware is the place for that kind of work.
Default middleware
configureStore adds a default set of middleware:
- The thunk middleware, which lets you dispatch functions.
createAsyncThunkrelies on it. - The immutability check, in development only. It throws if state is mutated outside a reducer.
- The serializability check, in development only. It warns if an action or state holds a value that is not serializable, such as a class instance or a function.
When you add your own middleware, use the callback form and call concat. This keeps the defaults in place.
import { configureStore } from '@reduxjs/toolkit'
const logger = (storeApi) => (next) => (action) => {
console.log('dispatching', action.type)
const result = next(action)
console.log('next state', storeApi.getState())
return result
}
export const store = configureStore({
reducer: {},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(logger),
})A middleware is three nested functions. The first receives the store API (dispatch and getState). The second receives next, which passes the action on to the following middleware. The third receives the action. If you never call next(action), the action stops there.
The listener middleware
The listener middleware runs code in response to actions. It is a good fit for effects that follow an action, such as saving a setting after it changes. You create it with createListenerMiddleware, register listeners, and add it to the store.
import {
configureStore,
createListenerMiddleware,
createSlice,
} from '@reduxjs/toolkit'
const settingsSlice = createSlice({
name: 'settings',
initialState: { theme: 'light' },
reducers: {
themeChanged(state, action) {
state.theme = action.payload
},
},
})
export const { themeChanged } = settingsSlice.actions
const listenerMiddleware = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: themeChanged,
effect: async (action, listenerApi) => {
localStorage.setItem('theme', action.payload)
console.log('state after reducer:', listenerApi.getState().settings.theme)
},
})
export const store = configureStore({
reducer: { settings: settingsSlice.reducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})Three details matter here:
- The
effectruns after the reducer has handled the action, sogetState()returns the new state. - You can match with
actionCreator,type,matcher, or apredicatefunction that sees the action and the state. - Call
prepend, notconcat, for the listener middleware. The Redux Toolkit docs recommend this order so that listeners see actions before other middleware changes them.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Default checks or thunk disappear | Passing an array: `middleware: [logger]` | Use the callback form with `getDefaultMiddleware().concat(...)` |
| Action never reaches the reducer | Middleware forgot to call `next(action)` | Call `next(action)` and return its result |
| Serializability warning | A non-serializable value in an action | Keep actions as plain data |
| Effect runs twice | Same listener registered twice | Register once at startup |
Exercise
Exercise
Why does the listener middleware example read listenerApi.getState().settings.theme inside the effect and get the new theme, and which method should you use to add the listener middleware to the default middleware list?
Show answer
Listener effects run after the reducer has processed the action, so getState() already holds the updated state. Add it with getDefaultMiddleware().prepend(listenerMiddleware.middleware).
Exercise
A custom middleware logs every action but the store stops updating. What is the most likely mistake?
Show answer
The middleware does not call next(action), so the action never reaches the following middleware or the reducer.