Reducer Mode
직접 setter를 호출하는 것보다 action으로 상태 변경 규칙을 모으는 편이 나을 때 사용합니다.
Named reducer state
createRxReducer는 state를 직접 바꾸지 않고 action을 dispatch합니다. 장바구니, todo, editor state처럼 변경 규칙이 여러 개인 상태에 적합합니다.
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",
);Runtime key에는 reducer tuple helper 사용
workspace id, project id처럼 runtime key마다 reducer store를 분리해야 한다면 createRxReducerTuple을 사용합니다.
tsx
export function useWorkspaceFilterState(workspaceId: string) {
return createRxReducerTuple(
initialFilterState,
filterReducer,
`workspace-filter:${workspaceId}`,
{ storage: "auto" },
);
}