What are Middlewares in React Redux?
Last Updated :
10 May, 2025
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.
Middleware Workflow in ReduxApproach 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
Middlewares in React ReduxIn 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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read