Understanding Redux Middleware

Sulenchy
Chingu
Published in
2 min readMay 16, 2019

Middleware

Simply put middleware is a software component which provides services to integrate disparate system together(Wikipedia). Middleware can also be functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle as stated on Expressjs. See the screenshot below:

Express middleware

Redux Middleware

Redux middleware is a snippet of code that provides a third-party extension point between dispatching an action and the moment it reaches the reducers.

See this

Note: All these happen within the store( the redux single source of truth). Every middleware has next() that calls the next action in the line.

It is a way to extend redux with custom functionality. They let you wrap the store’s dispatch method for fun and profit. There are a number of them available to you. They include redux-logger, redux-thunk, redux-promise etc. The redux-thunk extends the functionality of a normal redux action to return a function instead of an object of the new state. Redux-logger extends redux native functionality by introducing a logger to log actions when dispatching them before reducers reduce the state. See the screenshot below:

Note: In the left-hand side of the above screenshot, the store dispatches an object ({type: “SOME_EVENT}) while in the right-hand side, the store dispatches a function (() => {}).

ApplyMiddleware

This is a function packaged with redux that accepts one or more middlewares and returns a function. It is a store enhancer usually place after every other store enhancer you may use. The screenshot below shows how the applyMiddleware can be used to apply a number middleware to the store dispatch function.

Note: the applyMiddleware enhancer applies middlewares(c, d and others) to the store dispatch function

Snippet of Code

The snippet of code shown below shows how the applyMiddleware combine two redux middleware(Redux-logger and redux-thunk) and passed into the createStore function to wrap the store’s dispatch.

import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducers'
import reduxLogger from 'redux-logger'
import reduxThunk from 'redux-thunk'

const store = createStore(rootReducer, applyMiddleware(reduxLogger, reduxThunk))

In Conclusion, redux middleware is a means of extending the redux native functionalities. It wraps the store’s dispatch method for fun and profit. With the help applyMiddleware enhancer, you can apply a number of middlewares to redux store. Here is a block of code by radutz-san on Sandbox that briefly demonstrates how middleware, store’s dispatch, applyMiddleware and reducer connect together.

--

--