Redux の基本と初期化
Redux は、JavaScript アプリケーション(特に React アプリ)のための状態管理ライブラリです。
簡潔に説明すると:
- アプリケーション全体の状態を単一のストア(store)で集中管理します
- 状態は読み取り専用で、アクションを通じてのみ変更可能です
- 変更はリデューサー(reducer)と呼ばれる純粋関数によって行われます
基本的な概念:
- ストア(Store): アプリケーションの状態を保持する唯一の場所
- アクション(Action): 何が起きたかを表すプレーンなオブジェクト(type 属性が必須)
- リデューサー(Reducer): 現在の状態とアクションを受け取り、新しい状態を返す関数
- ディスパッチ(Dispatch): アクションをストアに送信するメソッド
簡単な例:
// アクションタイプの定義
const INCREMENT = "INCREMENT";
// アクションクリエイター
const increment = () => ({ type: INCREMENT });
// 初期状態
const initialState = { count: 0 };
// リデューサー
function counterReducer(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 };
default:
return state;
}
}
// ストアの作成
import { createStore } from "redux";
const store = createStore(counterReducer);
// Reactとの連携
import { Provider, useSelector, useDispatch } from "react-redux";
function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>カウント: {count}</p>
<button onClick={() => dispatch(increment())}>増加</button>
</div>
);
}
// アプリケーションにReduxを提供
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
useState と比較すると、Redux はアプリケーション全体の状態管理や複雑な状態ロジックを扱う場合に有用です。
おわりに
Claude 3.7 Sonnet で生成した、勉強会用のダミーデータです。