Understanding Redux middleware

Probably the easiest and best way of extending the Redux functionality is by using middleware.

There is a store enhancer function that comes in the Redux library named applyMiddleware and allows you define one or multiple middleware functions. The way middleware works in Redux is simple, it allows you to wrap the dispatch method of the store to extend its functionality. The same way as store enhancer functions, middleware is composable and has the following signature:

middleware = API => next => action => next(action) 

Here, API is an object containing the dispatch and getState methods from the store, destructuring the API, the signature looks like this:

middleware = ({ 
    getState, 
    dispatch, 
}) => next => action => next(action)  

Let's analyze how it works:

  1. The applyMiddleware function receives one or more middleware functions as arguments. For example:
      applyMiddleware(middleware1, middleware2) 
  1. Each middleware function is kept internally as an Array. Then, internally using the Array.prototype.map method, the array maps each middleware function by calling itself providing the middleware API object which contains the dispatch and getState methods of the store. Similar to this:
      middlewares.map((middleware) => middleware(API)) 
  1. Then, by composing all the middleware functions, it computes a new value for the dispatch method providing the next argument. In the very first middleware that is executed, the next argument refers to the original dispatch method before any middleware was applied. For instance, if applying three middleware functions, the new computed dispatch method's signature would be:
      dispatch = (action) => ( 
          (action) => ( 
              (action) => store.dispatch(action) 
          )(action) 
      )(action) 
  1. Which means that a middleware function can interrupt the chain and prevent a certain action from being dispatched if the next(action) method is not called
  2. The dispatch method from the middleware API object, allows you to call the dispatch method of the store with the previously applied middleware. That means, if you are not careful while using this method, you may create an infinite loop

Understanding how it works internally may not be so simple at first, but I assure you that you will get it soon.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.156.50