Middleware are a much more advanced technique than what we've looked at previously. In this lesson, we'll focus more on using them, rather than writing them. They'll help us to connect various libraries, and from the very beginning of using them in React.
Middleware are functions that are called sequentially when updating data in the store.
The general principle is like so:
This organization allows programmers to extend libraries with new functionality without rewriting the Redux source code for a specific task.
Middleware is used in tasks such as:
How middleware works:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducer,
/* preloadedState, */
applyMiddleware(thunk)
)
Above you can see the thunk middleware. Before passing it to the createStore
function, we need to apply the applyMiddleware
function to it. Note that we're passing the middleware as the second parameter, even though in the previous lesson the second parameter was initState
. This happens because the createStore
function checks the type of the second parameter, and understands what's in front of it depending on the type.
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, the result of the compose
function is passed to the store. The compose() function takes middleware as input.
And now we've arrived at the main point. There's a special browser extension, Redux DevTools, written especially 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're working 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. This will be your main debugging assistant throughout the course.
The Hexlet support team or other students will answer you.
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.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
From a novice to a developer. Get a job or your money back!
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.