Reducer 模式

當直接調用 setter 不如通過動作來集中狀態變更規則時使用。


命名的 reducer 狀態

createRxReducer不直接改變狀態,而是發送動作。適合有多個變更規則的狀態,如購物車、待辦事項、編輯器狀態。

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",
);

運行時鍵中使用 reducer 元組助手

如果需要為每個運行時鍵(如工作區 ID、專案 ID)分離 reducer 存儲, createRxReducerTuple則使用。

tsx
export function useWorkspaceFilterState(workspaceId: string) {
  return createRxReducerTuple(
    initialFilterState,
    filterReducer,
    `workspace-filter:${workspaceId}`,
    { storage: "auto" },
  );
}
© 2026 Byeolnaerim. 版權所有。介紹隱私政策