Writing Custom middlewares in React Redux
Last Updated :
02 Apr, 2024
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.
What is Redux middleware?
Redux middleware is a mechanism that sits between dispatching an action and the moment it reaches the reducer. It allows you to intercept actions and execute custom logic, such as logging, asynchronous operations, or modifying actions before they reach the reducers.
Custom middleware in Redux refers to user-defined functions that intercept actions dispatched to the store before they reach the reducers. These functions enable developers to add custom logic such as logging, modifying actions, or performing asynchronous operations.
When to use Custom Middleware?
Use custom middleware in Redux when you need to:
- Handle asynchronous operations such as API requests or timers.
- Perform logging, authentication, error handling, or data transformation.
- Monitor performance metrics for optimization purposes.
- Cache data locally to reduce API calls and improve performance.
Standard patterns to follow for creating custom middleware
When creating custom middleware for Redux, there are several standard patterns you can follow. These patterns allow you to create side effects for actions, modify or cancel actions, or modify the input accepted by dispatch. Here are some standard patterns for middleware:
- Creating Side Effects: Middleware can create side effects for actions by intercepting them before they reach reducers, allowing for tasks like logging, dispatching additional actions, or handling asynchronous operations.
- Modifying or Canceling Actions: Middleware can modify actions before they reach reducers, such as adding metadata or modifying payload data. It can also cancel actions altogether based on certain conditions.
- Modifying Input Accepted by Dispatch: Middleware can modify the input accepted by dispatch, enabling tasks like throttling or debouncing actions, or transforming data before it's dispatched.
Rules to make compatible middleware
To ensure compatibility and adherence to Redux middleware conventions, custom middleware should follow these rules:
- Calling the Next Middleware: Middleware functions should always call the next function to pass control to the next middleware in the chain. This ensures that all middleware in the stack have an opportunity to process the action.
JavaScript
const myMiddleware = store => next => action => {
// Perform some logic before passing the action
// to the next middleware
console.log('Middleware processing:', action);
// Call the next middleware in the chain
return next(action);
};
- Returning the Dispatch Return Value: Middleware should return the result of calling next(action), which is typically the return value of the dispatch function. This allows middleware further down the chain to access the return value of dispatch, which can be useful for composing middleware.
JavaScript
const myMiddleware = store => next => action => {
// Perform some logic before passing
// the action to the next middleware
console.log('Middleware processing:', action);
// Call the next middleware in the
// chain and return its return value
return next(action);
};
Steps to Setup React App and Installing Module:
Step 1: Create a new React application using Create React App:
npx create-react-app custom-middleware
Step 2: Navigate to the project directory:
cd custom-middleware
Project Structure:

Install Redux and React Redux:
npm install redux react-redux
The Updated dependencies in package.json file will look like.
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"web-vitals": "^2.1.4"
},
Step 3: Creating required folder and files
- Create redux folder inside src with customMiddleware.js ,store.js and reducers.js files
- replace code of App.js and index.js with the code given below.
JavaScript
// src/redux/reducers.js
const initialState = {
count: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
...state,
count: state.count + 1
};
default:
return state;
}
};
export default reducer;
JavaScript
// src/redux/customMiddleware.js
const customMiddleware = store => next => action => {
console.log('Custom Middleware - Dispatching action:', action);
// Pass the action to the next middleware or to the reducer
const result = next(action);
// You can also perform logic after the action has been dispatched
return result;
};
export default customMiddleware;
JavaScript
// src/redux/store.js
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import customMiddleware from './customMiddleware';
// Apply the custom middleware
const middlewareEnhancer = applyMiddleware(customMiddleware);
// Create the Redux store
const store = createStore(rootReducer, middlewareEnhancer);
export default store;
JavaScript
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
JavaScript
// src/App.js
import React from 'react';
import { connect } from 'react-redux';
const App = ({ count, increment }) => {
return (
<div>
<h1>Count: {count}</h1>
<button
onClick={increment}>
Increment
</button>
</div>
);
};
const mapStateToProps = state => ({
count: state.count
});
const mapDispatchToProps = dispatch => ({
increment: () => dispatch({ type: 'INCREMENT' })
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
Output:

Similar Reads
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 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 middlew
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
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
Action's Payload in React Redux
In the realm of React Redux, understanding how actions and their payloads work is fundamental to efficient state management. Actions serve as messengers that convey information from your application to the Redux store, triggering state updates. Among the key components of actions is the payload, whi
6 min read
Redux Thunk vs. Redux Saga: Choosing the Right Middleware
Redux, a predictable state container for JavaScript apps, is widely used in React applications for managing application state. Redux Thunk and Redux Saga are middleware libraries commonly employed with Redux for managing side effects such as asynchronous API calls, complex state transitions, and mor
3 min read
Write an overview of React Redux
React Redux is like a helper for your React application. It provides the way of communication link between the React and Redux. It helps them to talk smoothly. So, when you're building your app with React, and you need to grab some ingredients from the store (Redux), React Redux is there to help you
3 min read
Common middleware libraries used in Redux
Middleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements a
5 min read
How to Integrate Redux with React Components ?
Redux is an open-source JavaScript library for managing and centralizing application state. It helps you to write applications that behave consistently and are easy to test and run in different environments. It can also be understood as the predictable state container for the JavaScript app. It is m
4 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 C
4 min read