When a dispatch is made, the middleware intercepts the action before it reaches the reducer.
In the redux library’s createStore
function used to instantiate a store
. createStore
accepts three arguments: (reducer, preloadedState, enhancer)
Middleware is given to the store
via the optional enhancer
argument.
Ex:
// ./src/store.js
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger'; // third-party logger middleware
// the logger middleware prints the store's state before and after an action is processed.
import rootReducer from './reducers/rootReducer';
const configureStore = (preloadedState = {}) => {
return createStore(
rootReducer,
preloadedState,
applyMiddleware(logger),
);
};
export default configureStore;
A Redux middleware must always have the following signature:
const middleware = store => next => action => {
// swhatever logic we want to do
return next(action);
};
Middleware receives the store
as an argument and returns a function.
That function takes the next
link in the middleware chain as an argument and returns another function.
This function receives the action
and then triggers any side effects before returning the result of next(action)
.
Example of our own logger middleware: