useReducer関数の使いどころ
よく使われる状態管理フックuseStateと混合しがちですが、useStateは状態(値)のみを管理するのに対して、useReducerは状態(値)と状態を操作するための処理を管理するフックです。
useStaeとuseReducerの使い分け
| 状態管理フック | 使い分けポイント |
|---|---|
| useState | 状態(値)だけを管理したい場合 |
| useReducer | 状態(値)と処理の両方を管理したい場合 |
サンプルコード
Counter.tsx
import React,{ useReducer } from "react";
// 状態の型
type State = {
count:number;
}
// アクションの型
type Action =
|{type:'increment'}
|{type:'decrement'}
|{type:'reset'}
;
// reducer関数
function counterReducer(state:State,action:Action):State{
switch (action.type){
case 'increment':
return {count:state.count + 1};
case 'decrement':
return {count:state.count - 1};
case 'reset':
return {count:0};
default:
return state;
}
}
// コンポーネント本体
const Counter:React.FC = ()=>{
const [state,dispatch] = useReducer(counterReducer,{count:0});
return (
<div style={{ textAlign: 'center', marginTop: '2rem' }}>
<h1>useReducerカウンター</h1>
<p style={{ fontSize: '2rem' }}>{state.count}</p>
<div>
<button onClick={()=>dispatch({type:'increment'})}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>リセット</button>
</div>
</div>
);
}
export default Counter;
💡 説明
useReducer(reducer, initialState)は、useStateの代わりに状態遷移ロジックを外部化したいときに便利です。
reducer関数は(state, action) => newStateの形で、状態更新のルールを定義します。
dispatch()でアクションを送ることで状態を更新します。
App.tsx
import './App.css';
import Counter from './Counter';
function App() {
return (
<div>
<h1 data-testid="app-title">My React App</h1>
<Counter />
</div>
);
}
export default App;