frontend / state managers / redux / redux_middleware.md

Redux Middleware

4 interview angles 3 min read source

Redux Middleware

Redux middleware is a powerful extension point between dispatching an action and the moment it reaches the reducer. Middleware can intercept, modify, delay, or log actions, and is commonly used for handling side effects, logging, async operations, and more.

Table of Contents


What is Redux Middleware?

  • Middleware is a function that sits between action dispatch and the reducer.
  • It can intercept, modify, delay, or log actions.
  • Used for side effects, async logic, logging, analytics, etc.

Signature:

const middleware = store => next => action => {
  // Do something with action
  return next(action); // Pass action to next middleware/reducer
};

How does Middleware Work?

  • Middleware is applied using applyMiddleware when creating the Redux store.
  • Each middleware receives the store API (dispatch, getState), the next middleware, and the action.
  • Middleware can:
    • Pass the action to the next middleware/reducer
    • Stop the action
    • Dispatch new actions
    • Perform side effects

Example:

import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk, logger)
);

Usage Example

Custom logger middleware:

const logger = store => next => action => {
  console.log('Dispatching:', action);
  const result = next(action);
  console.log('Next state:', store.getState());
  return result;
};

Async middleware (thunk):

const thunk = store => next => action => {
  if (typeof action === 'function') {
    return action(store.dispatch, store.getState);
  }
  return next(action);
};

Common Middleware Types

  • redux-thunk: Handles async logic by allowing action creators to return functions.
  • redux-saga: Uses generator functions for complex async flows and side effects.
  • redux-logger: Logs actions and state changes for debugging.
  • Custom middleware: For analytics, error reporting, etc.

Best Practices

  • Use middleware for side effects, async logic, and cross-cutting concerns.
  • Keep middleware pure and focused.
  • Chain multiple middleware for complex needs.
  • Prefer established libraries (thunk, saga) for async logic.

Common Interview Questions

Q: What is the order of middleware execution?

  • Middleware is executed in the order it is applied to the store.

Q: Can middleware dispatch new actions?

  • Yes, middleware can dispatch new actions (e.g., for async flows).

Q: How do you write custom middleware?

  • Use the middleware signature and call next(action) to pass actions along.

Summary

  • Middleware extends Redux with custom logic between dispatch and reducer.
  • Commonly used for async, logging, analytics, and more.
  • Use applyMiddleware to add middleware to your store.

Interview angle

  • “What is Redux middleware?” - a function wrapping dispatch, composed into a chain, that sees every action before it reaches the reducer. It is where side effects, logging and async work live, because reducers must stay pure.
  • “Sketch the signature.” - store => next => action => next(action). Calling next passes it down the chain; not calling it swallows the action; dispatching from inside re-enters at the top, which is how thunks work.
  • “Do you need to add thunk manually?” - no, configureStore from Redux Toolkit includes it plus development checks for accidental mutation and non-serialisable values. Hand-rolling applyMiddleware is the legacy setup.
  • “Thunk or saga?” - thunks for the overwhelming majority: simple async calls, easy to read. Sagas when you need long-running, cancellable, coordinated flows - and even then, ask whether a query library removes the need entirely.