tezvyn:

Redux Middleware: Intercepting Actions Before Reducers

AI-drafted, machine-checkedSource: redux.js.orgadvanced

Redux middleware is like an Express middleware for your state, intercepting actions before they hit the reducer. It's used for logging, crash reporting, or async API calls. The footgun is forgetting to call `next(action)`, which silently blocks the action.

WHY IT EXISTS Redux by itself is synchronous and predictable. But what about side effects? How do you log every action, report crashes with state context, or talk to an API? Manually adding this logic everywhere you dispatch an action is repetitive and error-prone. Middleware was created to solve this by providing a single, centralized extension point for the dispatch process.

THE MENTAL MODEL Middleware is a function that wraps the store's dispatch method. Think of it as a customs agent for your actions. When an action is dispatched, it first goes through the middleware chain. Each middleware can inspect the action, do something with it (like log it), and then must decide whether to pass it on to the next agent (the next middleware or the reducer) by calling a function called next.

HOW IT WORKS A Redux middleware is a higher-order function with the signature store => next => action => .... It receives the store API, a next function, and the action. The next function represents the next middleware in the chain, or the original store.dispatch if it's the last one. Inside the middleware, you can execute code before and after calling next(action). For example, you can log the action, call next(action), and then log the new state from store.getState().

WHEN TO USE IT Use middleware for any logic that needs to happen as a result of an action being dispatched but isn't part of the pure state calculation. Three main places this shows up: first, for logging actions and state for debugging; second, for reporting errors to a third-party service; and third, for handling asynchronous operations like API calls (e.g., with redux-thunk or redux-saga).

WHEN NOT TO USE IT Do not put core business logic that directly calculates the next state inside middleware. That logic belongs in a reducer. Middleware is for side effects and cross-cutting concerns, not for state mutation. If your logic is just transforming one synchronous action into another, a reducer is often a simpler choice.

ONE CANONICAL EXAMPLE A simple logger middleware. It logs the action being dispatched, passes the action to the next middleware or reducer by calling next(action), and then logs the new state after the update. This demonstrates the core pattern of intercepting, acting, and forwarding. This was the original problem that led to the middleware concept in Redux.

Read the original → redux.js.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.