Tool for HR, Hiring Managers, and the Leadership Team

What is Middleware in Redux?

In Redux (interview perspective), middleware is a concept used to extend Redux functionality by intercepting actions before they reach the reducer.

What is Middleware in Redux?

Middleware is a function that sits between dispatching an action and the moment it reaches the reducer.

It allows you to:

  • Intercept actions

  • Modify actions

  • Log actions

  • Handle asynchronous logic (like API calls)

  • Dispatch new actions

Simple Flow

Without middleware:

dispatch(action) → reducer → store update

With middleware:

dispatch(action) → middleware → reducer → store update

Middleware can:

  • Stop an action

  • Pass it through

  • Dispatch another action

Why is Middleware Needed?

Redux reducers must be pure functions, so they cannot:

  • Call APIs

  • Perform async operations

  • Have side effects

Middleware solves this by handling side effects outside reducers.

Example Middleware (Logging)

const loggerMiddleware = store => next => action => {
  console.log("Dispatching:", action);
  let result = next(action);
  console.log("Next State:", store.getState());
  return result;
};

Explanation:

  • store: gives access to Redux store

  • next: passes action to next middleware/reducer

  • action: the dispatched action

Common Use Cases

1. Async API calls

Using libraries like:

  • redux-thunk

  • redux-saga

Example (redux-thunk):

const fetchUsers = () => {
  return async (dispatch) => {
    const res = await fetch("/api/users");
    const data = await res.json();

    dispatch({ type: "USERS_LOADED", payload: data });
  };
};

2. Logging actions

Useful for debugging Redux flow.

3. Error handling

Catch API or action-related errors globally.

4. Authentication checks

Block or modify actions based on user state.

How Middleware is Applied

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";

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

Interview Key Points (Must Say)

✔ Middleware sits between dispatch and reducer
✔ Used to handle side effects in Redux
✔ Helps in async operations like API calls
✔ Keeps reducers pure
✔ Can modify, delay, or log actions

One-line Answer

Middleware in Redux is a layer between dispatching an action and the reducer that allows interception, modification, and handling of side effects like asynchronous API calls.