ReactMedium

What is Middleware in Redux?

Redux middleware is a function that sits between dispatch and the reducers. Every dispatched action passes through the middleware chain, which can log it, modify it, stop it, delay it, dispatch other actions, or run side effects such as API calls. Its signature is store => next => action => { ... return next(action) }.

Common middleware

  • Thunk (included by default in Redux Toolkit): allows dispatching functions for async logic.
  • Listener middleware (createListenerMiddleware, RTK): run effects when specific actions or state changes occur. The modern alternative to sagas for most cases.
  • RTK Query middleware: manages cache lifetimes, polling and invalidation.
  • Redux Saga / Redux Observable: generator- or RxJS-based side effect orchestration.
  • Custom: logging, analytics, crash reporting, persistence, auth token handling.

How the chain works

configureStore({ middleware: (getDefault) => getDefault().concat(logger) }). Each middleware calls next(action) to pass the action on; code before next runs before reducers, code after runs after state updates.

Development checks

Redux Toolkit's default middleware includes checks for accidental state mutation and non-serializable values in development.

Guidelines

  • Keep reducers pure; put side effects in middleware, thunks or listeners.
  • Avoid heavy synchronous work in middleware: it runs on every dispatch.
  • Prefer RTK Query for data fetching over hand-written fetch middleware.

Code example

tsx
1import { configureStore, createListenerMiddleware, createSlice, type Middleware } from "@reduxjs/toolkit";
2
3const cart = createSlice({
4 name: "cart",
5 initialState: { items: [] as string[] },
6 reducers: { added: (s, a: { payload: string }) => void s.items.push(a.payload) },
7});
8
9// Custom middleware: log every action and the resulting state
10const logger: Middleware = (store) => (next) => (action) => {
11 console.log("dispatching", action);
12 const result = next(action); // pass to the next middleware / reducers
13 console.log("next state", store.getState());
14 return result;
15};
16
17// Listener middleware: side effect when a specific action happens
18const listener = createListenerMiddleware();
19listener.startListening({
20 actionCreator: cart.actions.added,
21 effect: async (action) => {
22 await fetch("/api/analytics", { method: "POST", body: JSON.stringify({ added: action.payload }) });
23 },
24});
25
26export const store = configureStore({
27 reducer: { cart: cart.reducer },
28 middleware: (getDefault) => getDefault().prepend(listener.middleware).concat(logger),
29});
30
31store.dispatch(cart.actions.added("pen"));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app