Trung BìnhState Management iconState Management

Redux middleware là gì? Cho ví dụ về middleware phổ biến?

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.

Xem toàn bộ State Management cùng filter theo level & chủ đề con.

Mở danh sách State Management