Open In App

What are Middlewares in React Redux?

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In React Redux, middlewares are an essential concept for handling side effects and enhancing the functionality of Redux. They are used to intercept actions sent to the Redux store and modify them before they reach the reducer or after they are dispatched.

Understanding Redux

Before diving into middlewares, let’s take a quick refresher on how Redux works:

  • Actions: Actions are plain JavaScript objects that describe an event or an intention to change the state.
  • Reducers: Reducers are functions that specify how the state of the application changes in response to actions.
  • Store: The store holds the state of the application and is responsible for dispatching actions to the reducers.

For more details follow this article => Introduction to Redux

Middleware Workflow in Redux

Here’s how middleware typically works in Redux:

1. Dispatching an action: When you dispatch an action, it first goes through the middleware before reaching the reducer.

2. Middleware Intercepts the Action: Middlewares can:

  • Modify the action.
  • Perform side effects (like API calls).
  • Dispatch additional actions.

3. Action Reaches Reducer: Once the middleware has completed its work, the action is passed to the reducer, which updates the application’s state based on the action.

4. Optional Post-Processing: After the action reaches the reducer, additional logic can be run.

REDUX-WORKFLOW-FEATURES
Middleware Workflow in Redux

Approach to implement Middleware in React Redux

  • Reducer (reducers.js): Define the initial state and a reducer function to manage a simple counter state in Redux.
  • Middleware (middleware/logger.js): Create a middleware to log each dispatched action and the updated state. This middleware intercepts actions, performs logging, and passes the action along to the next middleware or reducer.
  • Store (store/index.js): Set up the Redux store, apply the middleware, and export the configured store.
  • App Component (App.js): A simple React component displaying the counter, with buttons to increment and decrement the value. React Redux hooks (useSelector and useDispatch) are used to interact with the Redux store.
  • Provider (index.js): Wrap the App component with Provider from React Redux to make the Redux store available throughout the app

Steps to Create a Middleware in React

Step 1: To initialize the project type the below command in your terminal.

npx create-react-app middleware-react-redux

Step 2: Naviagte to the root directory of your application.

cd middleware-react-redux

Step 3: Install the required packages in your application using the following command.

npm install redux react-redux @reduxjs/toolkit

To create a middleware, we first need to import the applyMiddleware function from Redux like this:

import { applyMiddleware } from "redux";
JavaScript
// store/reducers.js
const initialState = {
    count: 0
};

const rootReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return {
                ...state,
                count: state.count + 1
            };
        case 'DECREMENT':
            return {
                ...state,
                count: state.count - 1
            };
        default:
            return state;
    }
};

export default rootReducer;
JavaScript
// store/middleware/logger.js

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

export default logger;
JavaScript
// store/index.js

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

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

export default store;
JavaScript
// App.js

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

function App() {
    const count = useSelector(state => state.count);
    const dispatch = useDispatch();

    const increment = () => {
        dispatch({ type: 'INCREMENT' });
    };

    const decrement = () => {
        dispatch({ type: 'DECREMENT' });
    };

    return (
        <div>
            <h1>Counter: {count}</h1>
            <button onClick={increment}>Increment</button>
            <button onClick={decrement}>Decrement</button>
        </div>
    );
}

export default App;
JavaScript
// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);
npm start

Output

rr
Middlewares in React Redux

In this example

  • store/reducers.js: Defines the initialState with a count property and a rootReducer to handle INCREMENT and DECREMENT actions to update the count.
  • store/middleware/logger.js: A custom middleware that logs each dispatched action and the new state after the action is processed.
  • store/index.js: Creates the Redux store, applies the logger middleware, and exports the store.
  • App.js: A React component that displays the counter value. It uses useSelector to read the state and useDispatch to dispatch INCREMENT and DECREMENT actions.
  • index.js: Wraps the App component in a Provider to provide the Redux store to the app, allowing components to access the state and dispatch actions.

Types of Middleware in Redux

Here are the main types of middleware in Redux:

  • Logging Middleware: Logs every action dispatched to Redux, useful for debugging (e.g., redux-logger).
  • Thunk Middleware (redux-thunk): Allows action creators to return functions (for handling async actions).
  • Promise Middleware (redux-promise): Handles actions that return promises and dispatches new actions based on promise resolution.
  • Saga Middleware (redux-saga): Manages complex asynchronous flows using generator functions.

How to Write Custom Middleware in Redux

Custom middleware can be written to extend Redux functionality. A middleware is a function that receives the Redux store’s dispatch and getState functions and returns another function that receives the action, allowing it to dispatch the next action in the chain.

Now let's understand this with the help of example:

JavaScript
const customLogger = store => next => action => {
    console.log('Dispatching Action: ', action);
    return next(action);
};

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

Why Should You Use Middleware?

Here are some of the main reasons why middleware is useful in Redux:

  • Handles Asynchronous Actions: Middleware enables us to manage async operations (like API calls) in a smooth way, which Redux alone doesn't support natively.
  • Logs Actions: It helps track actions and state changes, making debugging easier.
  • Manages Side Effects: Middleware allows us to handle side effects like analytics or logging without cluttering your reducers.
  • Extends Redux: It enhances Redux functionality without altering its core logic, enabling features like promises, thunks, or custom behaviors.

Conclusion

Middleware in React Redux is important for handling tasks like logging or making API calls before actions reach the reducer. It helps manage data and actions more effectively in an app. The example shows how to set up Redux with a custom middleware to update the counter state. Understanding and using middleware properly makes working with Redux simpler and more efficient.


Similar Reads