01
はじめに
Reducer
Reducer は (state, action) => state の純粋関数です。
redux
function counter(state = 0, action) {
switch (action.type) {
case "INCREMENT": return state + 1;
case "DECREMENT": return state - 1;
default: return state;
}
}Store
Store が状態を保持し、dispatch で状態を変更します。
redux
import { createStore } from "redux";
const store = createStore(counter);
store.dispatch({ type: "INCREMENT" });
console.log(store.getState());Redux Toolkit
Redux Toolkit の createSlice を使うと Redux のコードが簡単に書けます。
redux
import { createSlice, configureStore } from "@reduxjs/toolkit";
const counter = createSlice({
name: "counter",
initialState: 0,
reducers: {
increment: s => s + 1,
decrement: s => s - 1,
}
});
const store = configureStore({ reducer: counter.reducer });02
React 連携
useSelector
状態の読み取りとアクションの dispatch を行う Hooks です。
redux
import { useSelector, useDispatch } from "react-redux";
function Counter() {
const count = useSelector(s => s);
const dispatch = useDispatch();
return <button onClick={() => dispatch({type: "INCREMENT"})}>{count}</button>;
}Was this helpful?