🐡

Redux middlewareの実行タイミング確認サンプル

2021/01/02に公開

要点

  • applyMiddlaweの後ろにあるmiddlewareが内側になる
  • 初期化用のアクション(@@redux/INIT)はlistenerやmiddlewareで捕捉されない
  • state更新後はmidlewareよりlistenerが先に呼ばれる

middlewareイメージ

TODO 以下の図を書く

dispatch -> [ outer [ inner [ reducer -> listener ] inner ] outer ]

コード

import { createStore, applyMiddleware } from "redux";

const reducer = (state, action) => {
  console.log("reducer", action);
  return state;
};
const outerMiddleware = () => (next) => (action) => {
  console.log("outer middleware: before", action);
  next(action);
  console.log("outer middleware: after", action);
};
const innerMiddleware = () => (next) => (action) => {
  console.log("inner middleware: before", action);
  next(action);
  console.log("inner middleware: after", action);
};
const listener1 = () => console.log("listener 1");
const listener2 = () => console.log("listener 2");

const store = createStore(
  reducer,
  // 後ろにあるミドルウェアが内側になる
  applyMiddleware(outerMiddleware, innerMiddleware)
);

store.subscribe(listener1);
store.subscribe(listener2);
store.dispatch({ type: "empty" });

出力

reducer {type: "@@redux/INIT7.m.7.3.0.r"}
outer middleware: before {type: "empty"}
inner middleware: before {type: "empty"}
reducer {type: "empty"}
listener 1 
listener 2 
inner middleware: after {type: "empty"}
outer middleware: after {type: "empty"}

Playground

Discussion