What are Redux middleware and how do you write a custom one?

Answer

Redux middleware provides an extension point between dispatching an action and the moment it reaches the reducer. It intercepts every dispatched action, enabling logging, crash reporting, async operations, and more. The middleware signature: const myMiddleware = (store) => (next) => (action) => { console.log("Before:", store.getState()); const result = next(action); console.log("After:", store.getState()); return result; }. Register: configureStore({ reducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(myMiddleware) }). Common middleware: Redux Thunk (async), Redux-Saga (generator-based async), redux-logger (console logs), redux-observable (RxJS). Custom middleware examples: API middleware that intercepts type: "API_CALL" actions and makes fetch requests, analytics middleware that logs specific actions to analytics services, authorization middleware that adds auth headers. The three-level currying (store => next => action => ...) enables middleware composition — each middleware wraps the next, forming a chain.