Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Intermediate

What is Middleware?

Definition

Code you can put between the framework receiving a request, and the framework generating a response. In Redux, middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.

Explain Like I'm New

The bouncer at a club. Before an Action is allowed to enter the Reducer club, the Bouncer stops it. The Bouncer can inspect the action, log it to a computer, delay it, or completely throw it in the trash. Once the Bouncer is done, it lets the Action pass through.

Real World Example

Analytics. You write a middleware that intercepts EVERY action. If the action is `ADD_TO_CART`, the middleware secretly fires an event to Google Analytics before passing the action on to the reducer.

Common Use Cases

  • •Logging
  • •Crash reporting
  • •Routing async actions (Thunks)

Terminal Output

bash / terminal
/* The Redux Pipeline: 1. Component runs `dispatch({ type: 'ADD' })` │ ▼ 2. MIDDLEWARE 1 (e.g., Logger - Prints the action to the console) │ calls next() ▼ 3. MIDDLEWARE 2 (e.g., Thunk - Checks if action is a function. It's not, so it passes it on) │ calls next() ▼ 4. REDUCER (Catches the action and updates state) */

Interview Questions

basic

  • Does Middleware run BEFORE or AFTER the Reducer processes the action?

intermediate

  • Can Middleware stop an action from reaching the Reducer entirely?

Flash Cards

Question

Before or after?

Click to reveal answer
Answer

BEFORE. Middleware intercepts the action the exact moment it is dispatched.

Question

Can it stop actions?

Click to reveal answer
Answer

Yes! If a middleware function does not call `next(action)`, the action dies right there and the Reducer never sees it.