top of page
Logo der Online Agentur mdwp

Middleware

Middleware in React is often used in conjunction with Redux, a state management library. Middleware is basically a layer in between your Dispatch (actions you want to perform on your data) and your Reducer (which actually performs the action and returns new state).

The main idea behind middleware is to let us add custom functionality in the middle of/dispatch cycle like logging, error reporting, asynchronous API calls, etc.

Middleware functions usually have a structure like this:

```javascript
const myMiddleware = storeAPI => next => action => {
// Middleware code here...
const result = next(action);
return result;
};
```

- `storeApi` provides access to the `dispatch` and `getState`.
- `next` points to the next middleware in line or to the `dispatch` if the current middleware is the last one in the chain.
- `action` represents dispatched action.

Let's say you want to log every action that's dispatched:

```javascript
const loggerMiddleware = storeAPI => next => action => {
console.log('dispatching', action)
let result = next(action)
console.log('next state', storeAPI.getState())
return result
}
```
As can be seen in the above example, the middleware logs the action being dispatched and the new state after reducer has returned the new state.

All middleware is added when we create the store like so:

```javascript
import { createStore, applyMiddleware } from 'redux';
import { loggerMiddleware } from './middleware';

let store = createStore(
rootReducer,
applyMiddleware(loggerMiddleware)
);
```
With the above code, every time you dispatch an action - the `loggerMiddleware` will log a message to the console.

bottom of page