Middleware là function nằm giữa dispatch(action) và reducer, có thể inspect, modify, delay, hoặc cancel action trước khi đến reducer.
- Flow:
dispatch → middleware1 → middleware2 → reducer. - Middleware phổ biến:
redux-thunk(cho phép dispatch function thay vì object, xử lý async — RTK include mặc định),redux-saga(dùng generator functions cho complex async flows như race conditions, cancellation, debounce),redux-logger(log action type, prev state, next state — hữu ích cho debug).
Ví dụ custom middleware: const logger = store => next => action => { console.log(action.type); return next(action) }.
Pitfall: thứ tự middleware quan trọng — thunk phải ở đầu để dispatch(function) được xử lý trước khi đến middleware khác.