Hack Frontend Community

Redux Middleware

Redux Middleware is mechanism for extending Redux functionality that allows injecting additional logic between action dispatch and moment when it reaches reducer.

What Middleware is For

Middleware in Redux is used for:

  • Processing async operations
  • Logging actions
  • Error handling
  • Modifying actions before they reach reducer
  • Canceling actions

How Middleware Works

Middleware sits between dispatch and reducer, allowing to:

  • Intercept actions
  • Modify actions
  • Create new actions
  • Stop actions

Simple Middleware Example

const loggerMiddleware = store => next => action => {
  console.log('Previous state:', store.getState());
  console.log('Action:', action);
  
  const result = next(action);
  
  console.log('Next state:', store.getState());
  return result;
};

// Connecting middleware
const store = createStore(
  rootReducer,
  applyMiddleware(loggerMiddleware)
);
  • Redux Thunk: For async operations
  • Redux Saga: For complex async flows
  • Redux Observable: For reactive programming
  • Redux Logger: For debugging

Important:

Middleware should be used only when really necessary, as each additional middleware increases application complexity.