Middlewares are a much more advanced technique than everything we already know. In this lesson, we'll focus on using them rather than writing them. They will help us to connect various libraries from the beginning of using them in React.
Middleware is a function that we call sequentially when updating data in the store.
The general principle is like so:
- Middleware is initially built into the repository when we create it
- Then, during dispatching, the data passes through the middleware, and only then does it go into the reducer
This organization allows programmers to extend libraries with new functionality without rewriting the Redux source code for a specific task.
We can use middleware in tasks such as:
- Logging
- Error notification
- Working with asynchronous APIs
- Routing
How middleware works:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducer,
/* preloadedState, */
applyMiddleware(thunk)
)
Here you can see the thunk middleware. Before passing it to the createStore
function, we should apply the other one — applyMiddleware
.
Note that we're passing the middleware as the second parameter, even though we used initState
in the previous lesson.
It happens because the createStore
function checks the second parameter's type and understands what's in front of it depending on it.
If there is more than one piece of middleware, you'll have to use another function:
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
const store = createStore(
reducer,
/* preloadedState, */
compose(
applyMiddleware(thunk),
applyMiddleware(logger)
),
)
In this case, we pass the result of the compose
function to the store. The compose()
function takes middleware as input.
And now we've arrived at the main point. There is a browser extension, Redux DevTools, written for Redux. Install it in your browser.
Below is the code for connecting this extension to the repository:
const reduxDevtools = window.__REDUX_DEVTOOLS_EXTENSION__;
const store = createStore(
reducer,
/* preloadedState, */
reduxDevtools && reduxDevtools(),
);
Note that when we work with a function extension, we don't need applyMiddleware
.
In future lessons, you won't have to connect the extension yourself. We've already done it for you. All you need to do is install it and remember to use it. It will be your debugging assistant throughout the course.
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.