複雑な状態遷移をreduce関数で管理する。Reduxライクなパターンでコンポーネントの状態ロジックを整理できる。
const [state, dispatch] = useReducer(reducer, initialState)
type State = { count: number; status: 'idle' | 'loading' };
type Action =
| { type: 'INCREMENT' }
| { type: 'SET_LOADING'; payload: boolean };
function reducer(state: State, action: Action): State { ... }import { useReducer } from 'react';
type State = {
count: number;
history: number[];
};
type Action =
| { type: 'INCREMENT'; amount: number }
| { type: 'DECREMENT'; amount: number }
| { type: 'RESET' };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + action.amount, history: [...state.history, state.count] };
case 'DECREMENT':
return { count: state.count - action.amount, history: [...state.history, state.count] };
case 'RESET':
return { count: 0, history: [] };
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0, history: [] });
return (
<div>
<p>カウント: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT', amount: 1 })}>+1</button>
<button onClick={() => dispatch({ type: 'RESET' })}>リセット</button>
</div>
);
}useState が複数あって連動している場合や、次の状態が複数の前状態に依存する場合は useReducer が整理しやすい。