How to Use Middleware in Redux

redux-logo

Understanding Middleware in Redux

If you've used server-side libraries like Express you are probably already familiar with the concept of middleware. The middleware is some piece of code you can put between the framework receiving a request and the framework generating a response. The best thing about the middleware is that it's compostable in a chain.

In Redux, the middleware solves a different problem from the Express. Here the middleware provides an extension point between dispatching an action and reaching the reducer. The most common situation to use Redux middleware is for logging, crash reporting, asynchronous API calls, routing, and more.

redux-middleware-schema

How to use Middleware in Redux

The most basic example of using redux middleware is to log the action and the next state every time we are dispatching an action. To start using the middleware in redux firstly we need to import the applyMiddleware from redux package (the createStore and compose).

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';

Importing packages in index.js

const logger = store => {
  return next => {
    return action => {
      console.log('[Middleware] Dispatching', action);
      const result = next(action);
      console.log('[Middleware] next state', store.getState());
      return result;
    }
  }
}

logger function in index.js

Lastly, we just need to pass the applyMiddleware with the logger function as an argument inside the createStore function and we are done.

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(someReducer, composeEnhancers(applyMiddleware(logger)));

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

Putting all together in index.js

For more information on understanding redux middleware, the following are great resources:




#react #redux #js #javascript

Author: Aleksandar Vasilevski |

Loading...