top of page
Logo der Online Agentur mdwp

Redux Middleware

Redux Middleware, in the context of React Js, is a way to enhance Redux's base functionalities and provide extra capabilities that are not built into Redux itself. Middleware exists in a space between the dispatching of an action and the moment it reaches the reducer.

One common use of middleware is to support asynchronous actions without much additional code, by extending Redux's dispatch function. They can also be used for logging actions, crash reporting, talking to an asynchronous API, routing, and more.

Here is how you can apply a middleware:

import { createStore, applyMiddleware } from 'redux';
import MyMiddleware from './MyMiddleware';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(MyMiddleware));

In the above code, we are creating a Redux store. We are also enhancing this store with Redux's `applyMiddleware` function. This function is passed `MyMiddleware`, which is a custom middleware defined elsewhere in your codebase. This `MyMiddleware` can now intercept and operate on actions dispatched in the Redux store before they reach your application's reducers.

Here's an example of a simple custom middleware function that logs all actions that get dispatched to the console:

const MyMiddleware = store => next => action => {
console.log('Dispatching ', action);
let result = next(action);
console.log('Next state ', store.getState());
return result;

In the above code, `store` is the Redux store, `next` is the dispatch function, and `action` is the current action being processed. The middleware logs the action, then processes the action using `next(action)`, then logs the state after the action has been processed, and finally returns the result of `next(action)`. This example gives you a clear picture of what actions are occurring in your Redux store and their effects.

bottom of page