Redux is a state-management library, often used with React. In this article, I will teach you to write custom middleware to extend the capabilities of Redux and gain an in-depth understanding of how global state is managed.
The Redux docs are intended to teach the basic concepts of Redux, as well as explain key concepts for use in real-world applications. However, the docs can't cover everything. Happily, there are many other great resources available for learning Redux. We encourage you to check them out. Many of them cover topics that are beyond the scope of the docs, or describe the same topics in other ways that may work better for your learning style.
What is Redux? If you know what Redux is, feel free to skip to the next section. Redux is used to manage global state, most often in React applications. It does so by storing a global, immutable state object, which you can modify through reducers. A reducer is a function that takes a state object, an action (in other words, event) object and returns a new state object. The action object describes what exactly happened and how the state should be changed. An action object always has a type property, and optional payload properties. What is a middleware? Middleware in Redux is used to override the behavior of the store, most often the dispatch function. redux-thunk is one such middleware. It lets you dispatch asynchronous actions. Another example is redux-logger, which logs every action and state change to the console. The point of writing Redux custom middlewares is to implement some advanced features in a reusable and consistent way. It is supposed to simplify your development experience and clean up your code. Writing Redux custom middleware The idea of developing a custom redux middleware came to me when I encountered a problem at work. I had certain API requests to be made anytime a specific action was dispatched. Moreover, another team member had the exact same problem. I decided to develop a middleware that would allow you to intercept certain actions and provide callbacks for them. In this article, we will be developing a slightly modified version of the middleware we ended up using in production. Middleware is defined in a slightly confusing way. It is supposed to be a function that takes in the redux store and returns a function that takes in a callback next, which returns another function that takes in the redux action and performs the middleware feature you need. Do not worry, it would all be clear in a moment. You can notice that on line 2 we log the type of the action and pass the action to next. next pipelines the action to the next middleware or to the original dispatch, if there are no more middlewares. It is crucial to call next, otherwise, your action will not be dispatched. Order is also important: anything before next will be executed before the action is dispatched, anything after - after the action is dispatched.
GET THE SKILLS YOU NEED TO BECOME A FULL-STACK DEVELOPER