1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptでReduxをセットアップして初期状態を準備する方法

Posted at

今回はTypeScriptでReduxをセットアップして初期状態を準備する方法を記事にしたいと思います。

Reduxストアの作成
srcディレクトリ内にstoreフォルダを作成し、store.tsファイルを追加します。

src/store/store.ts

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

// RootStateとAppDispatchの型をエクスポート
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

スライスの作成
機能ごとの状態とロジックを管理するために、スライスを作成します。ここではカウンター機能のスライスを作成します。

src/features/counter/counterSlice.ts

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

export interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0, // 初期状態の設定
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: { payload: number }) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;

プロバイダーの設定
index.tsxファイルでProviderを使ってReduxストアをアプリケーションに提供します。

src/index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { store } from './store/store';
import { Provider } from 'react-redux';

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

コンポーネントでの状態の使用
App.tsxでReduxの状態とディスパッチ関数を使用します。

src/App.tsx

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from './store/store';
import { increment, decrement, incrementByAmount } from './features/counter/counterSlice';

function App() {
  const count = useSelector((state: RootState) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>カウント: {count}</h1>
      <button onClick={() => dispatch(increment())}>増加</button>
      <button onClick={() => dispatch(decrement())}>減少</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>5増加</button>
    </div>
  );
}

export default App;

アプリの起動
設定が完了したので、アプリケーションを起動して動作を確認します。

npm start

ブラウザでhttp://localhost:3000にアクセスし、カウンター機能が正しく動作することを確認してください。

まとめ

Redux Toolkitを使用することで、ボイラープレートを削減し、よりシンプルに状態管理を実装できます。

参考資料
Redux公式ドキュメント
Redux Toolkit公式ドキュメント
React Redux公式ドキュメント

毎日更新していますので、@y-t0910をフォロー,いいねしていただけると嬉しいです。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?