Reducer Mode

Sử dụng khi việc tập hợp quy tắc thay đổi trạng thái bằng action tốt hơn là gọi trực tiếp setter.


Trạng thái reducer được đặt tên

tạoRxReducerdispatch action mà không thay đổi trực tiếp state. Phù hợp cho các trạng thái có nhiều quy tắc thay đổi như giỏ hàng, todo, trạng thái editor.

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

Sử dụng reducer tuple helper cho runtime key.

Nếu cần tách biệt reducer store cho mỗi runtime key như workspace id, project id. createRxReducerTuplesẽ được sử dụng.

tsx
export function useWorkspaceFilterState(workspaceId: string) {
  return createRxReducerTuple(
    initialFilterState,
    filterReducer,
    `workspace-filter:${workspaceId}`,
    { storage: "auto" },
  );
}
© 2026 Byeolnaerim. Bảo lưu mọi quyền.Giới thiệuChính sách xử lý thông tin cá nhân