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.
Previous
What is the difference between local state, global state, and server state?
Next
How do you architect state management for large-scale React applications?
More Redux / State Management Questions
View all →- Intermediate How do you handle async operations in Redux Toolkit with createAsyncThunk?
- Intermediate What is Zustand's middleware system?
- Intermediate What is Reselect and memoized selectors?
- Intermediate How does normalized state shape work in Redux?
- Intermediate What is the Flux architecture pattern?