🔖

Reduxを理解したい

に公開

状態管理ツールとしてメジャーどころの「Reux」を今回理解するための備忘録を残すことにする

まずvscodeにて「redux」をインストール
npm install @reduxjs/toolkit react-redux

そもそもこれで何をインストールしているのかわからないので、早速AIに質問

1. @reduxjs/toolkit

Redux公式の推奨ツールキット
従来のReduxを簡単に使えるようにしたもの
含まれる主な機能:

  • configureStore: Storeの設定を簡単に
  • createSlice: reducer + actionsを自動生成
  • createAsyncThunk: 非同期処理の管理

2. react-redux

ReactでReduxを使うための公式バインディング
主な機能:

  • <Provider>: Redux StoreをReactアプリ全体に提供
  • useSelector: Storeから状態を取得するフック
  • useDispatch: アクションをディスパッチするフック

なぜ2つ必要?

@reduxjs/toolkit = Redux本体(状態管理のロジック)
react-redux = ReactとReduxを繋ぐ橋渡し`

では早速作成していきましょう

1.Sliceを作る

なんのために?

  • 「何を管理するか」を定義
  • カウンターなら:初期値0、増やす・減らすアクション
  • これが状態管理の核心部分

以下のような感じで作成しました。

import { createSlice , PayloadAction} from '@reduxjs/toolkit';

// 状態の型定義
interface UserState {
    id : number;
    name : string;
    email : string;
}

// 初期状態
const initialState : UserState = {
    id: 0,
    name: "",
    email : "",
}

// Sliceの作成
const userSlice = createSlice({
    name:"user",
    initialState,
    reducers:{
        setUser:(state , action:PayloadAction<UserState>)=>{
            state.id = action.payload.id;
            state.name = action.payload.name;
            state.email = action.payload.email;
        },
        deleteUser:(state)=>{
            state.id = 0;
            state.name = "";
            state.email = "";
        },
    },
});

export const { setUser , deleteUser } = userSlice.actions;

export default userSlice.reducer;

今回、学習のために「counterSlice」と「UserSlice」の二つのファイルを用意しました。

2.storeを作る

なんのために?

  • 複数のSliceを一箇所に集約
  • アプリ全体で状態を共有するため
  • 状態の構造を定義
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counterSlice';
import userReducer from './features/userSlice';
import App from 'next/app';

export const makeStore = () => {
    return configureStore({
        reducer : {
            counter : counterReducer,
            user : userReducer,
        },
    });
};

export type AppStore = ReturnType<typeof makeStore>;
export type AppState = ReturnType<AppStore['getState']>;
export type AppDispatch = AppStore['dispatch'];

3.型安全なhooksを作成

なんのために?

  • 現状だと、以下のように毎回型を指定する必要が出てくる
  // 型指定なしだと
const count = useSelector(state => state.counter.value); // 型エラーの可能性

// 毎回型を指定すると
const count = useSelector((state: AppState) => state.counter.value);
const dispatch: AppDispatch = useDispatch();
// ↑ これを毎回書くのは面倒で、書き忘れも起こる

ということで、以下のように作成

import { useDispatch ,useSelector } from "react-redux";
import type { AppState , AppDispatch } from "./store";

export const useAppDispatch = () => useDispatch<AppDispatch>();

export const useAppSelector = <T>(selector : (state : AppState ) => T) => 
    useSelector(selector);

3.プロバイダーを作成

なんのために?

  • アプリ全体でReduxStoreを使えるようにするため
    こちらはapp/に作成します。
    理由としては、まずclientComponentである("use client"が必要)、そしてUIレイヤーの一部である。
    またlibはロジック用のフォルダであるため
"use client";

import { useRef } from "react";
import { Provider } from "react-redux";
import { makeStore , AppStore } from "@/lib/store";

export default function StoreProvider({
    children,
}:{
    children : React.ReactNode;
}) {
    // 再レンダリングを防ぐために useRef を使用
    const storeRef = useRef<AppStore | null>(null);

    if(!storeRef.current) {
        storeRef.current = makeStore();
    }

    return (
        <Provider store={storeRef.current}>
            {children}
        </Provider>
    );
}

4.アプリ全体をプロバイダーで囲む

layout.tsxを3で作成したプロバイダーで囲みます。

import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import StoreProvider from "./StoreProvider";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        //ここで囲う
        <StoreProvider>
          {children}
        </StoreProvider>
      </body>
    </html>
  );
}

これで準備完了

5.各コンポーネントで使用してみる

"use client";

import { useAppDispatch , useAppSelector } from "@/lib/hooks";
import { increment , decrement , reset , incrementByAmount } from "@/lib/features/counterSlice";

export default function ReduxPage() {
    const count = useAppSelector((state) => state.counter.value);
    const dispatch = useAppDispatch();

    return (
        <div className="flex min-h-screen items-center justify-center">
            <div className="max-w-2xl p-8">
                <h1 className="text-4xl font-bold mb-8 text-center">
                    Redux Page
                </h1>
                <div className="text-center mb-6">
                    <p className="text-2xl mb-4">Count: {count}</p>
                    <button
                        onClick={() => dispatch(increment())}
                        className="mx-2 px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
                    >
                        Increment
                    </button>
                    <button
                        onClick={() => dispatch(decrement())}
                        className="mx-2 px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
                    >
                        Decrement
                    </button>
                    <button
                        onClick={() => dispatch(reset())}
                        className="mx-2 px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600"
                    >
                        Reset
                    </button>
                    <button
                        onClick={() => dispatch(incrementByAmount(count))}
                        className="mx-2 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
                    >
                        Increment by {count}
                    </button>
                </div>
            </div>
        </div>
    );
}

ライブラリを使用してのReduxだったので、あまり細かいところまでは触れられていないのかもしれないですが、なんとか完成してよかった

Discussion