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
What are middlewares in React Redux ?
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 ReduxBefore diving into middle
5 min read
What is Logger middleware in React Redux ?
Logger middleware is a tool that helps users understand what's happening behind the scenes in their Redux-powered React applications. It logs information about each action that gets dispatched in your app, along with the state before and after the action is processed. Syntax:import { createStore, ap
3 min read
Writing Custom middlewares in React Redux
Custom middleware in React Redux is like having a helper that can do things with actions before they're handled by our app. It allows us to intercept actions and apply custom logic before they reach the reducers. In this article, we are going to discuss how it is done. Table of Content What is Redux
5 min read
Creating custom middlewares in React Redux
In React-Redux applications, managing the flow of data is crucial for building efficient and scalable apps. Redux provides a powerful state management solution, and custom middleware adds an extra layer of flexibility to handle complex scenarios effectively. Let's understand custom middleware in sim
5 min read
What are combinedReducers in React Redux?
In React Redux 'combinedReducers' is like putting together smaller pieces of a puzzle (reducers) to form one big puzzle (the root reducer). It helps manage your application state more efficiently by organizing and combining these smaller pieces, making your code cleaner and easier to maintain. Key F
3 min read
What Are Props in React?
Props are read-only inputs passed to a React component. They are used to pass dynamic values like strings, arrays, objects, or functions, making components flexible and reusable. [GFGTABS] JavaScript function Greet(props) { return <h1>Hello, {props.name}!</h1>; } function App() { return
3 min read
Why we need Redux in React ?
Redux is a library used in JavaScript applications for managing application states. It is particularly used and more popular in terms of building single-page applications using frameworks like React. Redux can also be used with other frameworks or libraries as well. It serves as a centralized store
7 min read
What are Action's creators in React Redux?
In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects. Action
4 min read
What are the features of ReactJS ?
Created by Facebook, ReactJS is a JavaScript library designed for crafting dynamic and interactive applications, elevating UI/UX for web and mobile platforms. Operating as an open-source, component-based front-end library, React is dedicated to UI design and streamlines code debugging by employing a
4 min read
What is the use of middleware Redux Saga ?
What is Redux Saga?Redux Saga is a middleware library for Redux that provides an elegant way to handle side effects in your React applications. Side effects can include asynchronous actions like making API calls, managing WebSocket connections, and more. Before we dive into the implementation detail
5 min read