Blog>
Snippets

Logging Actions and States with Middleware in Redux 5.0.0

A realistic example of how to implement a logging middleware in Redux 5.0.0 that logs all actions and subsequent state changes to the console for debugging purposes.
const loggerMiddleware = store => next => action => {
    console.log('dispatching', action);
    let result = next(action);
    console.log('next state', store.getState());
    return result;
};
Defines a logging middleware that logs an action and the next state after the action is dispatched.
import { applyMiddleware, createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(
    rootReducer,
    applyMiddleware(loggerMiddleware)
);
Sets up the Redux store and applies the logging middleware so that it can log actions and subsequent state changes.