0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React + Redux Toolkit + nanoid でユニークID付きの状態管理を実装してみた

Posted at

こんにちは。今日は React + Redux Toolkit を使って、状態(state)にユニークなIDを付けて管理するシンプルなアプリを作りながら学んだことをまとめます。

🎯 目的
Redux Toolkit を使って状態管理する

nanoid() でユニークなIDを生成する

useSelector, useDispatch の基本的な使い方を理解する

状態の変更フロー(作動形)を把握する

📦 使用した技術
React(create-react-app)

Redux Toolkit

nanoid

🧱 ディレクトリ構成
css
복사
편집
src/
├── app/
│ └── store.js
├── features/
│ └── whiteboard/
│ └── whiteboardSlice.js
├── App.jsx
└── main.jsx
1️⃣ Redux store の作成(store.js)
js
복사
편집
import { configureStore } from '@reduxjs/toolkit';
import whiteboardReducer from '../features/whiteboard/whiteboardSlice';

export const store = configureStore({
reducer: {
ワイトボード: whiteboardReducer,
},
});
2️⃣ slice の作成(whiteboardSlice.js)
js
복사
편집
import { createSlice } from '@reduxjs/toolkit';

const whiteboardSlice = createSlice({
name: "whiteboard",
initialState: [],
reducers: {
作成: (state, action) => {
console.log("作成アクション:", action.payload);
return [...state, action.payload]; // 不変性を保つ
},
},
});

export const { 作成 } = whiteboardSlice.actions;
export default whiteboardSlice.reducer;
3️⃣ React コンポーネント(App.jsx)
js
복사
편집
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { 作成 } from './features/whiteboard/whiteboardSlice';
import { nanoid } from 'nanoid';

function App() {
const [入力文字, set入力文字] = useState("");
const ワイトボード = useSelector((state) => state.ワイトボード);
const dispatch = useDispatch();

const 作成する = () => {
const データ = { 番号: nanoid(), 内容: 入力文字 };
dispatch(作成(データ));
set入力文字("");
};

return (


ワイトボード



{ワイトボード.map((文字情報) => (

{文字情報.内容}

))}

<input
value={入力文字}
onChange={(e) => set入力文字(e.target.value)}
/>
作成する

);
}

export default App;
✅ 今日学んだポイント
nanoid() を使えばユニークIDが一瞬で作れる

useDispatch でアクションを発行して、状態を変更できる

useSelector で Redux store の状態を監視できる

Redux Toolkit の slice は reducer と action を同時に管理できて便利

状態は直接変更せず、...state を使って不変性を保つ

🔚 まとめ
nanoid() を使えば、UIやリストの key 管理がとても簡単になり、Redux の状態管理と組み合わせることで効率的に開発できます。
また、状態の「作動の流れ(Action → Reducer → Store)」を理解することで、より安全でバグの少ないコードが書けるようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?