Redux は、単一方向のデータフローに基づいて予測可能な状態管理を実現する JavaScript 向け状態コンテナです。
コア概念と Store の生成
import { createStore } from 'redux';
// Reducer: 次の状態を算出する純粋関数
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'counter/incremented':
return { value: state.value + 1 };
case 'counter/decremented':
return { value: state.value - 1 };
default:
return state;
}
}
// Store の作成
const store = createStore(counterReducer);
// 状態変更の購読
const unsubscribe = store.subscribe(() => {
console.log('現在のステート:', store.getState());
});
// Action のディスパッチ
store.dispatch({ type: 'counter/incremented' }); // { value: 1 }
store.dispatch({ type: 'counter/decremented' }); // { value: 0 }
Action Creator と Middleware
// Action Creator 関数
const incrementBy = (amount) => ({
type: 'counter/incrementBy',
payload: amount
});
// Middleware パターン (ログ記録、非同期処理 thunk 等)
const loggerMiddleware = (storeAPI) => (next) => (action) => {
console.log('Action ディスパッチ中:', action);
const result = next(action);
console.log('次のステート:', storeAPI.getState());
return result;
};
React Redux Hooks (useSelector と useDispatch)
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
export function Counter() {
const count = useSelector((state) => state.value);
const dispatch = useDispatch();
return (
<div>
<span>Count: {count}</span>
<button onClick={() => dispatch({ type: 'counter/incremented' })}>
+
</button>
</div>
);
}
最新の Redux Toolkit (RTK)
現在の Redux アプリケーションでは、定型コードを大幅に削減できる Redux Toolkit が標準です:
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; }
}
});
export const { increment, decrement } = counterSlice.actions;
export const store = configureStore({ reducer: counterSlice.reducer });