Saad Hassan

@syedsaadh

How Redux Middlewares can be helpful for you

Scale Your React Web Application with Redux Middlewares

When it comes to state management in React, Redux is quite popular and does the required job efficiently. Though dispatching actions and updating the store with reducers works great with simple Web Applications, Redux provides a powerful functionality of middlewares which makes your life easy in building a large scale web application.

It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.

As the documentation suggests, Redux middlewares work in a similar manner as express middlewares do ( if you come from server-side ). Someway between Action Creators and Reducer, the Middleware intercepts the action object before Reducer receives it and gives the functionality to perform additional actions or any enhancements with respect to the action dispatched.

Redux Middleware

Redux Middleware Syntax

export const fn = store => next => action => 
{
next(action);
...
}

This is what redux middleware looks like. And Collection of these middlewares are applied to your `createStore` function.

import { createStore, applyMiddleware, compose, combineReducers } from "redux";
const store = createStore(
combineReducers({
...reducers,
}),
compose(applyMiddleware(...middlewares))
);

Where to Use Middlewares?

Let’s take an example of Login Flow.

When the user submits the login form, what we need is to create an api request for authentication of the credentials provided and also show feedback like spinners, success and error notification on authentication response received from the server.

Now when you think of this flow then you will observe that you need to dispatch multiple actions with respect to a single action asynchronously. The Advanced Redux pattern by Nir Kaufman explains this type of pattern as the split of action to atomic actions that are responsible for separate functionalities. Similarly, you can have multiple action processing patterns in your middleware which do the required task.

We will be using Split and Filter for our use case, firstly our middleware will filter actions that are responsible for the LOGIN Flow. I like to make middlewares based on atomic flows like Login, Signup, GetBooks etc. For each filtered Action we will split and dispatch two actions, one of which will be responsible for Spinner on the UI and other for asynchronous api request to fetch the data. Also if the network request fails or the authentication fails we will dispatch “showError ” action accordingly.

export const logInFlow = store => next => action => {
next(action);
  if (action.type === "LOGIN_REQUEST") 
{
.... Create rq(Api Request) Here

dispatch(apiRequest(rq, "LOGIN_SUCCESS", "LOG_IN_FAILED"));
dispatch(showSpinner());
}
  if (action.type === types.LOGIN_SUCCESS) 
{
dispatch(hideSpinner());
dispatch(setToken(action.payload.token));
}
  if (action.type === types.LOGIN_FAILED) 
{
dispatch(hideSpinner());
dispatch(
showError(
"inline",
action.payload.errorMessage,
"Error Occured while Logging you in.",
"LOGIN_FAILED"
)
);
}
};

For each action, the reducer will be responsible for updating the state.

export default function sessionReducer(state = initState, action) {
switch (action.type) {
case types.LOGIN_SUCCESS: {
return {
...state,
isAuthenticated: true
};
}
case types.LOG_OUT: {
return { ...state, isAuthenticated: false };
}
default:
return state;
}
}

For larger Applications, I would suggest that you make multiple reducers and combine them.

Now you will be getting the picture of how middlewares help for intercepting actions for adding various processing patterns that help you to make your state management easy. Though there is some extra effort to create middleware for each functionality flow as your codebase grows this way helps in maintenance and refactoring.

That's it. I hope this would have given you quite a picture where Redux middlewares can provide benefits to your React Application.

I would recommend the talk https://www.youtube.com/watch?v=JUuic7mEs-s by Nir Kaufman if you need more depth towards action processing patterns.

Cheers 🎉🎊.

More by Saad Hassan

Topics of interest

More Related Stories