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?