リデューサーモード

直接setterを呼び出すよりも、アクションで状態変更ルールを集約する方が良い場合に使用します。


名前付きリデューサー状態

createRxReducerは状態を直接変更せずにアクションをディスパッチします。カート、todo、エディタ状態のように変更ルールが複数ある状態に適しています。

tsx
type TodoAction =
  | { type: "add"; text: string }
  | { type: "toggle"; id: number }
  | { type: "clearDone" };

function todoReducer(state: TodoState, action: TodoAction): TodoState {
  switch (action.type) {
    case "add":
      return {
        items: [...state.items, { id: state.nextId, text: action.text, done: false }],
        nextId: state.nextId + 1,
      };
    case "toggle":
      return {
        ...state,
        items: state.items.map((item) =>
          item.id === action.id ? { ...item, done: !item.done } : item,
        ),
      };
    default:
      return state;
  }
}

const { dispatchTodo, useTodo } = createRxReducer(
  initialTodoState,
  todoReducer,
  "todo",
);

ランタイムキーにはリデューサータプルヘルパーを使用

ワークスペースID、プロジェクトIDのようにランタイムキーごとにリデューサーストアを分離する必要がある場合 createRxReducerTupleを使用します。

tsx
export function useWorkspaceFilterState(workspaceId: string) {
  return createRxReducerTuple(
    initialFilterState,
    filterReducer,
    `workspace-filter:${workspaceId}`,
    { storage: "auto" },
  );
}
© 2026 Byeolnaerim. 無断転載を禁じます。紹介プライバシーポリシー