Blog>
Snippets

Redux Middleware Logging Actions

Example of custom middleware in Redux v5.0.0 to log actions for debugging purposes, showing how middleware intercepts and logs actions before they reach the reducer.
const loggerMiddleware = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result
}
This is a custom middleware that logs all dispatched actions and the resulting new state. It uses the Redux middleware signature with curried functions. When an action is dispatched, it is logged before it reaches the reducer, after which the action is passed down to the next middleware or reducer, and then the new state is logged.
const createStoreWithMiddleware = applyMiddleware(loggerMiddleware)(createStore)
// Use the above function to create your store
const store = createStoreWithMiddleware(rootReducer)
This code applies the loggerMiddleware to the Redux store upon creation using the applyMiddleware function provided by Redux. The middleware will now intercept every action dispatched to the store and perform the logging as defined in the middleware.