本文へスキップ

モダンReduxへの移行

学習内容
  • レガシーな「手書き」ReduxロジックをRedux Toolkitを使用して最新化する手順
  • レガシーなReact-Reduxの`connect`コンポーネントをフックAPIを使用して最新化する手順
  • TypeScriptを使用するReduxロジックとReact-Reduxコンポーネントを最新化する手順

概要

Reduxは2015年から存在しており、Reduxコードの記述に関する推奨パターンは長年にわたって大きく変化しています。Reactが`createClass`から`React.Component`、そしてフックを使用した関数コンポーネントへと進化したのと同様に、Reduxも手動によるストア設定+オブジェクトスプレッドを使用した手書きのReducer+React-Reduxの`connect`から、Redux Toolkitの`configureStore`+`createSlice`+React-ReduxのフックAPIへと進化しました。

多くのユーザーは、これらの「モダンRedux」パターンが存在する以前から存在する古いReduxコードベースに取り組んでいます。これらのコードベースを今日の推奨されるモダンReduxパターンに移行することにより、はるかに小さく、保守しやすいコードベースになります。

朗報は、**コードをモダンReduxに段階的に、少しずつ移行でき、古いReduxコードと新しいReduxコードが共存して動作する**ということです!

このページでは、既存のレガシーReduxコードベースを最新化するために使用できる一般的なアプローチと技術について説明します。

情報

Redux ToolkitとReact-Reduxフックを使用した「モダンRedux」がReduxの使用をどのように簡素化するかの詳細については、次の追加リソースを参照してください。

Redux Toolkitを使用したReduxロジックの最新化

Reduxロジックの移行における一般的なアプローチは次のとおりです。

  • 既存の手動Reduxストア設定をRedux Toolkitの`configureStore`に置き換えます。
  • 既存のスライスReducerとその関連するアクションを選択します。それらをRTKの`createSlice`で置き換えます。Reducerごとに1つずつ繰り返します。
  • 必要に応じて、既存のデータ取得ロジックをRTK Queryまたは`createAsyncThunk`で置き換えます。
  • 必要に応じて、`createListenerMiddleware`や`createEntityAdapter`などのRTKの他のAPIを使用します。

**常に、レガシーな`createStore`呼び出しを`configureStore`で置き換えることから始めるべきです。**これは一度限りのステップであり、既存のすべてのReducerとミドルウェアはそのまま動作し続けます。`configureStore`には、意図しないミューテーションやシリアライズできない値などの一般的な間違いに対する開発モードチェックが含まれているため、これらを導入することで、これらの間違いが発生しているコードベースの領域を特定するのに役立ちます。

情報

**Redux Fundamentals、パート8:Redux Toolkitを使用したモダンRedux**で、この一般的なアプローチを実際に行っている様子を確認できます。

`configureStore`を使用したストア設定

典型的なレガシーReduxストア設定ファイルは、いくつかの異なる手順を実行します。

  • スライスReducerをルートReducerに結合する。
  • ミドルウェアエンハンサーを作成する(通常はthunkミドルウェアを使用し、開発モードでは`redux-logger`などの他のミドルウェアを使用する)。
  • Redux DevToolsエンハンサーを追加し、エンハンサーを組み合わせて構成する。
  • `createStore`を呼び出す。

既存のアプリケーションでは、これらの手順は次のようになります。

src/app/store.js
import { createStore, applyMiddleware, combineReducers, compose } from 'redux'
import thunk from 'redux-thunk'

import postsReducer from '../reducers/postsReducer'
import usersReducer from '../reducers/usersReducer'

const rootReducer = combineReducers({
posts: postsReducer,
users: usersReducer
})

const middlewareEnhancer = applyMiddleware(thunk)

const composeWithDevTools =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const composedEnhancers = composeWithDevTools(middlewareEnhancer)

const store = createStore(rootReducer, composedEnhancers)

これらの手順はすべて、Redux Toolkitの`configureStore` APIへの単一の呼び出しで置き換えることができます。.

RTKの`configureStore`は元の`createStore`メソッドをラップし、ストア設定の大部分を自動的に処理します。実際には、効果的に1つのステップに削減できます。

基本的なストア設定:src/app/store.js
import { configureStore } from '@reduxjs/toolkit'

import postsReducer from '../reducers/postsReducer'
import usersReducer from '../reducers/usersReducer'

// Automatically adds the thunk middleware and the Redux DevTools extension
const store = configureStore({
// Automatically calls `combineReducers`
reducer: {
posts: postsReducer,
users: usersReducer
}
})

`configureStore`への1回の呼び出しですべての作業が完了しました。

  • `combineReducers`を呼び出して`postsReducer`と`usersReducer`をルートReducer関数に結合し、`{posts, users}`のようなルート状態を処理します。
  • そのルートReducerを使用してReduxストアを作成するために`createStore`を呼び出しました。
  • thunkミドルウェアを自動的に追加し、`applyMiddleware`を呼び出しました。
  • 意図しない状態のミューテーションなどの一般的な間違いをチェックするためのミドルウェアを自動的に追加しました。
  • Redux DevTools Extension接続を自動的に設定しました。

ストアの設定に追加の手順が必要な場合(追加のミドルウェアの追加、thunkミドルウェアへの`extra`引数の渡し、永続化されたルートReducerの作成など)、それを行うこともできます。以下は、組み込みミドルウェアのカスタマイズとRedux-Persistの有効化を示すより大きな例で、`configureStore`を使用するためのいくつかのオプションを示しています。

詳細な例:永続化とミドルウェアを使用したカスタムストア設定

この例では、Reduxストアを設定する際に発生する可能性のあるいくつかの一般的なタスクを示しています。

  • Reducerを個別に結合する(他のアーキテクチャ上の制約のために必要になる場合があります)。
  • 追加のミドルウェアを条件付きと無条件の両方で追加する。
  • APIサービスレイヤーなど、"extra argument"をthunkミドルウェアに渡す。
  • シリアライズできないアクションタイプを特別に処理する必要があるRedux-Persistライブラリを使用する。
  • 本番環境でdevtoolsをオフにし、開発環境で追加のdevtoolsオプションを設定する。

これらはどれも必須ではありませんが、現実世界のコードベースでは頻繁に現れます。

カスタムストア設定:src/app/store.js
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import { PersistGate } from 'redux-persist/integration/react'
import logger from 'redux-logger'

import postsReducer from '../features/posts/postsSlice'
import usersReducer from '../features/users/usersSlice'
import { api } from '../features/api/apiSlice'
import { serviceLayer } from '../features/api/serviceLayer'

import stateSanitizerForDevtools from './devtools'
import customMiddleware from './someCustomMiddleware'

// Can call `combineReducers` yourself if needed
const rootReducer = combineReducers({
posts: postsReducer,
users: usersReducer,
[api.reducerPath]: api.reducer
})

const persistConfig = {
key: 'root',
version: 1,
storage
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

const store = configureStore({
// Pass previously created persisted reducer
reducer: persistedReducer,
middleware: getDefaultMiddleware => {
const middleware = getDefaultMiddleware({
// Pass in a custom `extra` argument to the thunk middleware
thunk: {
extraArgument: { serviceLayer }
},
// Customize the built-in serializability dev check
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
}
}).concat(customMiddleware, api.middleware)

// Conditionally add another middleware in dev
if (process.env.NODE_ENV !== 'production') {
middleware.push(logger)
}

return middleware
},
// Turn off devtools in prod, or pass options in dev
devTools:
process.env.NODE_ENV === 'production'
? false
: {
stateSanitizer: stateSanitizerForDevtools
}
})

`createSlice`を使用したReducerとアクション

典型的なレガシーReduxコードベースでは、Reducerロジック、アクションクリエイター、アクションタイプが別々のファイルに分散されており、これらのファイルはタイプ別に別々のフォルダーにあることがよくあります。Reducerロジックは`switch`文と、オブジェクトスプレッドと配列マッピングを使用した手書きのイミュータブル更新ロジックを使用して記述されています。

src/constants/todos.js
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
src/actions/todos.js
import { ADD_TODO, TOGGLE_TODO } from '../constants/todos'

export const addTodo = (id, text) => ({
type: ADD_TODO,
text,
id
})

export const toggleTodo = id => ({
type: TOGGLE_TODO,
id
})
src/reducers/todos.js
import { ADD_TODO, TOGGLE_TODO } from '../constants/todos'

const initialState = []

export default function todosReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO: {
return state.concat({
id: action.id,
text: action.text,
completed: false
})
}
case TOGGLE_TODO: {
return state.map(todo => {
if (todo.id !== action.id) {
return todo
}

return {
...todo,
completed: !todo.completed
}
})
}
default:
return state
}
}

Redux Toolkitの`createSlice` APIは、Reducer、アクション、イミュータブル更新の記述におけるすべての「ボイラープレート」を排除するために設計されました!

Redux Toolkitを使用すると、レガシーコードに複数の変更が加えられます。

  • `createSlice`は、手書きのアクションクリエイターとアクションタイプを完全に排除します。
  • `action.text`や`action.id`などの固有の名前を持つフィールドはすべて、`action.payload`で置き換えられます。これは、個々の値、またはこれらのフィールドを含むオブジェクトのいずれかになります。
  • Immerのおかげで、手書きのイミュータブル更新は、Reducer内での「ミューテーション」ロジックで置き換えられます。
  • コードの種類ごとに別々のファイルを用意する必要はありません。
  • 特定のReducerに関するすべてのロジックを単一のスライスファイルにまとめることを推奨しています。
  • 「コードの種類」別に別々のフォルダを用意する代わりに、「機能」別にファイルを整理することをお勧めします。関連するコードは同じフォルダに配置します。
  • 理想的には、Reducerとアクションの名前は過去形を使用し、「起こったこと」を記述する必要があります。「今すぐこれをする」という命令形ではなく、`ADD_TODO`ではなく`todoAdded`などです。

定数、アクション、Reducerの別々のファイルは、すべて単一のスライスファイルに置き換えられます。最新化されたスライスファイルは次のようになります。

src/features/todos/todosSlice.js
import { createSlice } from '@reduxjs/toolkit'

const initialState = []

const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
// Give case reducers meaningful past-tense "event"-style names
todoAdded(state, action) {
const { id, text } = action.payload
// "Mutating" update syntax thanks to Immer, and no `return` needed
state.todos.push({
id,
text,
completed: false
})
},
todoToggled(state, action) {
// Look for the specific nested object to update.
// In this case, `action.payload` is the default field in the action,
// and can hold the `id` value - no need for `action.id` separately
const matchingTodo = state.todos.find(todo => todo.id === action.payload)

if (matchingTodo) {
// Can directly "mutate" the nested object
matchingTodo.completed = !matchingTodo.completed
}
}
}
})

// `createSlice` automatically generated action creators with these names.
// export them as named exports from this "slice" file
export const { todoAdded, todoToggled } = todosSlice.actions

// Export the slice reducer as the default export
export default todosSlice.reducer

`dispatch(todoAdded('Buy milk'))`を呼び出すと、`todoAdded`アクションクリエイターに渡す単一の値が、自動的に`action.payload`フィールドとして使用されます。複数の値を渡す必要がある場合は、`dispatch(todoAdded({id, text}))`のようにオブジェクトとして渡します。あるいは、`createSlice` Reducer内の「prepare」表記を使用して、複数の個別の引数を受け入れ、`payload`フィールドを作成することもできます。「prepare」表記は、アクションクリエイターが追加の作業(各アイテムの一意なIDの生成など)を実行していた場合にも役立ちます。

Redux Toolkitは、フォルダやファイルの構造、アクションの名前を特に気にしませんが、これらは推奨されるベストプラクティスです。なぜなら、これにより、より保守可能で分かりやすいコードになることが分かっているからです。

RTK Queryを使用したデータ取得

React+Reduxアプリでの典型的なレガシーデータ取得には、多くの構成要素とコードの種類が必要です。

  • 「リクエスト開始」、「リクエスト成功」、「リクエスト失敗」アクションを表すアクションクリエイターとアクションタイプ。
  • アクションをディスパッチし、非同期リクエストを行うThunk。
  • ローディング状態を追跡し、キャッシュされたデータを保存するReducer。
  • ストアからこれらの値を読み取るセレクター。
  • マウント後にコンポーネントでThunkをディスパッチする(クラスコンポーネントでは`componentDidMount`、関数コンポーネントでは`useEffect`を使用)。

これらは通常、多くの異なるファイルに分割されます。

src/constants/todos.js
export const FETCH_TODOS_STARTED = 'FETCH_TODOS_STARTED'
export const FETCH_TODOS_SUCCEEDED = 'FETCH_TODOS_SUCCEEDED'
export const FETCH_TODOS_FAILED = 'FETCH_TODOS_FAILED'
src/actions/todos.js
import axios from 'axios'
import {
FETCH_TODOS_STARTED,
FETCH_TODOS_SUCCEEDED,
FETCH_TODOS_FAILED
} from '../constants/todos'

export const fetchTodosStarted = () => ({
type: FETCH_TODOS_STARTED
})

export const fetchTodosSucceeded = todos => ({
type: FETCH_TODOS_SUCCEEDED,
todos
})

export const fetchTodosFailed = error => ({
type: FETCH_TODOS_FAILED,
error
})

export const fetchTodos = () => {
return async dispatch => {
dispatch(fetchTodosStarted())

try {
// Axios is common, but also `fetch`, or your own "API service" layer
const res = await axios.get('/todos')
dispatch(fetchTodosSucceeded(res.data))
} catch (err) {
dispatch(fetchTodosFailed(err))
}
}
}
src/reducers/todos.js
import {
FETCH_TODOS_STARTED,
FETCH_TODOS_SUCCEEDED,
FETCH_TODOS_FAILED
} from '../constants/todos'

const initialState = {
status: 'uninitialized',
todos: [],
error: null
}

export default function todosReducer(state = initialState, action) {
switch (action.type) {
case FETCH_TODOS_STARTED: {
return {
...state,
status: 'loading'
}
}
case FETCH_TODOS_SUCCEEDED: {
return {
...state,
status: 'succeeded',
todos: action.todos
}
}
case FETCH_TODOS_FAILED: {
return {
...state,
status: 'failed',
todos: [],
error: action.error
}
}
default:
return state
}
}
src/selectors/todos.js
export const selectTodosStatus = state => state.todos.status
export const selectTodos = state => state.todos.todos
src/components/TodosList.js
import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchTodos } from '../actions/todos'
import { selectTodosStatus, selectTodos } from '../selectors/todos'

export function TodosList() {
const dispatch = useDispatch()
const status = useSelector(selectTodosStatus)
const todos = useSelector(selectTodos)

useEffect(() => {
dispatch(fetchTodos())
}, [dispatch])

// omit rendering logic here
}

多くのユーザーはデータ取得の管理にredux-sagaライブラリを使用している可能性があり、その場合、sagaをトリガーするために追加の「シグナル」アクションタイプを使用している可能性があり、このsagaファイルはthunkの代わりに使用されます。

src/sagas/todos.js
import { put, takeEvery, call } from 'redux-saga/effects'
import {
FETCH_TODOS_BEGIN,
fetchTodosStarted,
fetchTodosSucceeded,
fetchTodosFailed
} from '../actions/todos'

// Saga to actually fetch data
export function* fetchTodos() {
yield put(fetchTodosStarted())

try {
const res = yield call(axios.get, '/todos')
yield put(fetchTodosSucceeded(res.data))
} catch (err) {
yield put(fetchTodosFailed(err))
}
}

// "Watcher" saga that waits for a "signal" action, which is
// dispatched only to kick off logic, not to update state
export function* fetchTodosSaga() {
yield takeEvery(FETCH_TODOS_BEGIN, fetchTodos)
}

そのコード全体をRedux Toolkitの「RTK Query」データ取得およびキャッシュレイヤーで置き換えることができます!

RTK Queryを使用すると、データ取得の管理のためにあらゆるアクション、thunk、reducer、セレクター、またはエフェクトを記述する必要がなくなります。(実際には、内部的にそれらのツールをすべて使用しています。)さらに、RTK Queryは、読み込み状態の追跡、リクエストの重複排除、およびキャッシュデータのライフサイクルの管理(不要になった期限切れデータの削除を含む)を処理します。

移行するには、単一のRTK Query「APIスライス」定義を設定し、生成されたreducerとミドルウェアをストアに追加します

src/features/api/apiSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const api = createApi({
baseQuery: fetchBaseQuery({
// Fill in your own server starting URL here
baseUrl: '/'
}),
endpoints: build => ({})
})
src/app/store.js
import { configureStore } from '@reduxjs/toolkit'

// Import the API object
import { api } from '../features/api/apiSlice'
// Import any other slice reducers as usual here
import usersReducer from '../features/users/usersSlice'

export const store = configureStore({
reducer: {
// Add the generated RTK Query "API slice" caching reducer
[api.reducerPath]: api.reducer,
// Add any other reducers
users: usersReducer
},
// Add the RTK Query API middleware
middleware: getDefaultMiddleware =>
getDefaultMiddleware().concat(api.middleware)
})

次に、取得およびキャッシュする特定のデータを表す「エンドポイント」を追加し、各エンドポイントに対して自動生成されたReactフックをエクスポートします。

src/features/api/apiSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const api = createApi({
baseQuery: fetchBaseQuery({
// Fill in your own server starting URL here
baseUrl: '/'
}),
endpoints: build => ({
// A query endpoint with no arguments
getTodos: build.query({
query: () => '/todos'
}),
// A query endpoint with an argument
userById: build.query({
query: userId => `/users/${userId}`
}),
// A mutation endpoint
updateTodo: build.mutation({
query: updatedTodo => ({
url: `/todos/${updatedTodo.id}`,
method: 'POST',
body: updatedTodo
})
})
})
})

export const { useGetTodosQuery, useUserByIdQuery, useUpdateTodoMutation } = api

最後に、コンポーネントでフックを使用します。

src/features/todos/TodoList.js
import { useGetTodosQuery } from '../api/apiSlice'

export function TodoList() {
const { data: todos, isFetching, isSuccess } = useGetTodosQuery()

// omit rendering logic here
}

createAsyncThunkを使用したデータ取得

データ取得には特にRTK Queryの使用をお勧めします。ただし、一部のユーザーからは、まだその段階に移行する準備ができていないというご意見をいただいています。その場合、少なくともRTKのcreateAsyncThunkを使用して、手書きのthunkとreducerの定型コードを削減できます。これにより、アクションクリエイターとアクションタイプが自動的に生成され、リクエストを行うために指定した非同期関数が呼び出され、promiseのライフサイクルに基づいてこれらのアクションがディスパッチされます。createAsyncThunkを使用した同じ例は次のようになります。

src/features/todos/todosSlice
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = {
status: 'uninitialized',
todos: [],
error: null
}

const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
// Just make the async request here, and return the response.
// This will automatically dispatch a `pending` action first,
// and then `fulfilled` or `rejected` actions based on the promise.
// as needed based on the
const res = await axios.get('/todos')
return res.data
})

export const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
// any additional "normal" case reducers here.
// these will generate new action creators
},
extraReducers: builder => {
// Use `extraReducers` to handle actions that were generated
// _outside_ of the slice, such as thunks or in other slices
builder
.addCase(fetchTodos.pending, (state, action) => {
state.status = 'loading'
})
// Pass the generated action creators to `.addCase()`
.addCase(fetchTodos.fulfilled, (state, action) => {
// Same "mutating" update syntax thanks to Immer
state.status = 'succeeded'
state.todos = action.payload
})
.addCase(fetchTodos.rejected, (state, action) => {
state.status = 'failed'
state.todos = []
state.error = action.error
})
}
})

export default todosSlice.reducer

セレクターも記述する必要があり、useEffectフック内でfetchTodos thunkを自分でディスパッチする必要があります。

createListenerMiddlewareを使用したリアクティブロジック

多くのReduxアプリには、特定のアクションまたは状態の変化をリスンし、それに応じて追加のロジックを実行する「リアクティブ」スタイルのロジックがあります。これらの動作は、多くの場合、redux-sagaまたはredux-observableライブラリを使用して実装されています。

これらのライブラリは、さまざまなタスクに使用されます。基本的な例として、アクションをリスンし、1秒待ってから追加のアクションをディスパッチするsagaとepicは次のようになります。

src/sagas/ping.js
import { delay, put, takeEvery } from 'redux-saga/effects'

export function* ping() {
yield delay(1000)
yield put({ type: 'PONG' })
}

// "Watcher" saga that waits for a "signal" action, which is
// dispatched only to kick off logic, not to update state
export function* pingSaga() {
yield takeEvery('PING', ping)
}
src/epics/ping.js
import { filter, mapTo } from 'rxjs/operators'
import { ofType } from 'redux-observable'

const pingEpic = action$ =>
action$.pipe(ofType('PING'), delay(1000), mapTo({ type: 'PONG' }))
src/app/store.js
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { combineEpics, createEpicMiddleware } from 'redux-observable';

// skip reducers

import { pingEpic } from '../sagas/ping'
import { pingSaga } from '../epics/ping

function* rootSaga() {
yield pingSaga()
}

const rootEpic = combineEpics(
pingEpic
);

const sagaMiddleware = createSagaMiddleware()
const epicMiddleware = createEpicMiddleware()

const middlewareEnhancer = applyMiddleware(sagaMiddleware, epicMiddleware)

const store = createStore(rootReducer, middlewareEnhancer)

sagaMiddleware.run(rootSaga)
epicMiddleware.run(rootEpic)

RTKの「リスナー」ミドルウェアは、よりシンプルなAPI、より小さなバンドルサイズ、そしてより優れたTSサポートにより、sagaとobservableを置き換えるように設計されています。

sagaとepicの例は、次のようにリスナーミドルウェアで置き換えることができます。

src/app/listenerMiddleware.js
import { createListenerMiddleware } from '@reduxjs/toolkit'

// Best to define this in a separate file, to avoid importing
// from the store file into the rest of the codebase
export const listenerMiddleware = createListenerMiddleware()

export const { startListening, stopListening } = listenerMiddleware
src/features/ping/pingSlice.js
import { createSlice } from '@reduxjs/toolkit'
import { startListening } from '../../app/listenerMiddleware'

const pingSlice = createSlice({
name: 'ping',
initialState,
reducers: {
pong(state, action) {
// state update here
}
}
})

export const { pong } = pingSlice.actions
export default pingSlice.reducer

// The `startListening()` call could go in different files,
// depending on your preferred app setup. Here, we just add
// it directly in a slice file.
startListening({
// Match this exact action type based on the action creator
actionCreator: pong,
// Run this effect callback whenever that action is dispatched
effect: async (action, listenerApi) => {
// Listener effect functions get a `listenerApi` object
// with many useful methods built in, including `delay`:
await listenerApi.delay(1000)
listenerApi.dispatch(pong())
}
})
src/app/store.js
import { configureStore } from '@reduxjs/toolkit'

import { listenerMiddleware } from './listenerMiddleware'

// omit reducers

export const store = configureStore({
reducer: rootReducer,
// Add the listener middleware _before_ the thunk or dev checks
middleware: getDefaultMiddleware =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware)
})

ReduxロジックのTypeScriptの移行

TypeScriptを使用するレガシーReduxコードは、通常、型の定義に非常に冗長なパターンに従います。特に、コミュニティの多くのユーザーは、個々のアクションごとにTS型を手動で定義し、「アクションタイプユニオン」を作成して、実際にdispatchに渡すことができる特定のアクションを制限しようとしました。

これらのパターンは強くお勧めしません!

src/actions/todos.ts
import { ADD_TODO, TOGGLE_TODO } from '../constants/todos'

// ❌ Common pattern: manually defining types for each action object
interface AddTodoAction {
type: typeof ADD_TODO
text: string
id: string
}

interface ToggleTodoAction {
type: typeof TOGGLE_TODO
id: string
}

// ❌ Common pattern: an "action type union" of all possible actions
export type TodoActions = AddTodoAction | ToggleTodoAction

export const addTodo = (id: string, text: string): AddTodoAction => ({
type: ADD_TODO,
text,
id
})

export const toggleTodo = (id: string): ToggleTodoAction => ({
type: TOGGLE_TODO,
id
})
src/reducers/todos.ts
import { ADD_TODO, TOGGLE_TODO, TodoActions } from '../constants/todos'

interface Todo {
id: string
text: string
completed: boolean
}

export type TodosState = Todo[]

const initialState: TodosState = []

export default function todosReducer(
state = initialState,
action: TodoActions
) {
switch (action.type) {
// omit reducer logic
default:
return state
}
}
src/app/store.ts
import { createStore, Dispatch } from 'redux'

import { TodoActions } from '../actions/todos'
import { CounterActions } from '../actions/counter'
import { TodosState } from '../reducers/todos'
import { CounterState } from '../reducers/counter'

// omit reducer setup

export const store = createStore(rootReducer)

// ❌ Common pattern: an "action type union" of all possible actions
export type RootAction = TodoActions | CounterActions
// ❌ Common pattern: manually defining the root state type with each field
export interface RootState {
todos: TodosState
counter: CounterState
}

// ❌ Common pattern: limiting what can be dispatched at the types level
export type AppDispatch = Dispatch<RootAction>

Redux ToolkitはTSの使用を大幅に簡素化するように設計されており、推奨事項にはできる限り型を推論することが含まれます!

標準のTypeScript設定と使用方法のガイドラインに従って、ストアファイルを設定して、ストア自体からAppDispatchRootStateの型を直接推論することから始めます。これにより、thunkをディスパッチする機能など、ミドルウェアによって追加されたdispatchへの変更が正しく含まれ、スライスの状態定義を変更したり、スライスを追加するたびにRootState型が更新されます。

app/store.ts
import { configureStore } from '@reduxjs/toolkit'
// omit any other imports

const store = configureStore({
reducer: {
todos: todosReducer,
counter: counterReducer
}
})

// Infer the `RootState` and `AppDispatch` types from the store itself

// Inferred state type: {todos: TodosState, counter: CounterState}
export type RootState = ReturnType<typeof store.getState>

// Inferred dispatch type: Dispatch & ThunkDispatch<RootState, undefined, UnknownAction>
export type AppDispatch = typeof store.dispatch

各スライスファイルは、独自のリーススライスの状態の型を宣言してエクスポートする必要があります。次に、PayloadAction型を使用して、createSlice.reducers内のaction引数の型を宣言します。生成されたアクションクリエイターは、受け入れる引数の正しい型と、返すaction.payloadの型も持つようになります。

src/features/todos/todosSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface Todo {
id: string
text: string
completed: boolean
}

// Declare and export a type for the slice's state
export type TodosState = Todo[]

const initialState: TodosState = []

const todosSlice = createSlice({
name: 'todos',
// The `state` argument type will be inferred for all case reducers
// from the type of `initialState`
initialState,
reducers: {
// Use `PayloadAction<YourPayloadTypeHere>` for each `action` argument
todoAdded(state, action: PayloadAction<{ id: string; text: string }>) {
// omit logic
},
todoToggled(state, action: PayloadAction<string>) {
// omit logic
}
}
})

React-Reduxを使用したReactコンポーネントの最新化

コンポーネント内のReact-Reduxの使用を移行する一般的なアプローチは次のとおりです。

  • 既存のReactクラスコンポーネントを関数コンポーネントに移行します。
  • connectラッパーを、コンポーネントuseSelectoruseDispatchフックの使用に置き換えます。

これは、コンポーネントごとに個別に実行できます。connectとフックを使用するコンポーネントは同時に共存できます。

このページでは、クラスコンポーネントを関数コンポーネントに移行するプロセスについては説明しませんが、React-Reduxに固有の変更に焦点を当てます。

connectからフックへの移行

React-Reduxのconnect APIを使用する一般的なレガシーコンポーネントは次のようになります。

src/features/todos/TodoListItem.js
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

// A `mapState` function, possibly using values from `ownProps`,
// and returning an object with multiple separate fields inside
const mapStateToProps = (state, ownProps) => {
return {
todo: selectTodoById(state, ownProps.todoId),
activeTodoId: selectActiveTodoId(state)
}
}

// Several possible variations on how you might see `mapDispatch` written:

// 1) a separate function, manual wrapping of `dispatch`
const mapDispatchToProps = dispatch => {
return {
todoDeleted: id => dispatch(todoDeleted(id)),
todoToggled: id => dispatch(todoToggled(id))
}
}

// 2) A separate function, wrapping with `bindActionCreators`
const mapDispatchToProps2 = dispatch => {
return bindActionCreators(
{
todoDeleted,
todoToggled
},
dispatch
)
}

// 3) An object full of action creators
const mapDispatchToProps3 = {
todoDeleted,
todoToggled
}

// The component, which gets all these fields as props
function TodoListItem({ todo, activeTodoId, todoDeleted, todoToggled }) {
// rendering logic here
}

// Finished with the call to `connect`
export default connect(mapStateToProps, mapDispatchToProps)(TodoListItem)

React-ReduxフックAPIを使用すると、connect呼び出しとmapState/mapDispatch引数はフックに置き換えられます!

  • mapStateで返される個々のフィールドは、それぞれ個別のuseSelector呼び出しになります。
  • mapDispatchを介して渡される各関数は、コンポーネント内で定義された個別のコールバック関数になります。
src/features/todos/TodoListItem.js
import { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
todoAdded,
todoToggled,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

export function TodoListItem({ todoId }) {
// Get the actual `dispatch` function with `useDispatch`
const dispatch = useDispatch()

// Select values from the state with `useSelector`
const activeTodoId = useSelector(selectActiveTodoId)
// Use prop in scope to select a specific value
const todo = useSelector(state => selectTodoById(state, todoId))

// Create callback functions that dispatch as needed, with arguments
const handleToggleClick = () => {
dispatch(todoToggled(todoId))
}

const handleDeleteClick = () => {
dispatch(todoDeleted(todoId))
}

// omit rendering logic
}

異なる点の1つは、connectが、入力されるstateProps+dispatchProps+ownPropsが変更されない限り、ラップされたコンポーネントのレンダリングを防ぐことでレンダリングのパフォーマンスを最適化していたことです。フックはコンポーネントの内部にあるため、それを行うことはできません。Reactの通常の再帰的なレンダリング動作を防ぐ必要がある場合は、コンポーネントを自分でReact.memo(MyComponent)でラップします。

コンポーネントのTypeScriptの移行

connectの主な欠点の1つは、非常に正しく型付けするのが難しく、型宣言が非常に冗長になることです。これは、高階コンポーネントであることと、APIの柔軟性の高さ(4つの引数、すべてオプション、それぞれに複数の可能性のあるオーバーロードとバリエーションがあります)が原因です。

コミュニティは、複雑さのレベルが異なる、これに対処する方法に関する複数のバリエーションを考案しました。低レベルでは、一部の使用法ではmapState()stateの型付けが必要であり、その後、コンポーネントのすべてのプロップの型を計算していました。

シンプルなconnectのTS例
import { connect } from 'react-redux'
import { RootState } from '../../app/store'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

interface TodoListItemOwnProps {
todoId: string
}

const mapStateToProps = (state: RootState, ownProps) => {
return {
todo: selectTodoById(state, ownProps.todoId),
activeTodoId: selectActiveTodoId(state)
}
}

const mapDispatchToProps = {
todoDeleted,
todoToggled
}

type TodoListItemProps = TodoListItemOwnProps &
ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps

function TodoListItem({
todo,
activeTodoId,
todoDeleted,
todoToggled
}: TodoListItemProps) {}

export default connect(mapStateToProps, mapDispatchToProps)(TodoListItem)

特にtypeof mapDispatchをオブジェクトとして使用することは危険でした。なぜなら、thunkが含まれている場合に失敗するからです。

他のコミュニティ作成のパターンでは、mapDispatchを関数として宣言し、bindActionCreatorsを呼び出してdispatch: Dispatch<RootActions>型を渡すか、ラップされたコンポーネントによって受信されるすべてのプロップの型を手動で計算して、それらをジェネリックとしてconnectに渡すなど、はるかに多くのオーバーヘッドが必要でした。

やや優れた代替手段は、v7.xで@types/react-reduxに追加されたConnectedProps<T>型であり、connectからコンポーネントに渡されるすべてのプロップの型を推論することができました。この推論を正しく機能させるには、connectへの呼び出しを2つの部分に分割する必要がありました。

ConnectedProps<T>のTS例
import { connect, ConnectedProps } from 'react-redux'
import { RootState } from '../../app/store'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

interface TodoListItemOwnProps {
todoId: string
}

const mapStateToProps = (state: RootState, ownProps) => {
return {
todo: selectTodoById(state, ownProps.todoId),
activeTodoId: selectActiveTodoId(state)
}
}

const mapDispatchToProps = {
todoDeleted,
todoToggled
}

// Call the first part of `connect` to get the function that accepts the component.
// This knows the types of the props returned by `mapState/mapDispatch`
const connector = connect(mapStateToProps, mapDispatchToProps)
// The `ConnectedProps<T> util type can extract "the type of all props from Redux"
type PropsFromRedux = ConnectedProps<typeof connector>

// The final component props are "the props from Redux" + "props from the parent"
type TodoListItemProps = PropsFromRedux & TodoListItemOwnProps

// That type can then be used in the component
function TodoListItem({
todo,
activeTodoId,
todoDeleted,
todoToggled
}: TodoListItemProps) {}

// And the final wrapped component is generated and exported
export default connector(TodoListItem)

React-ReduxフックAPIは、TypeScriptとの使用がはるかに簡単です!コンポーネントのラップ、型の推論、ジェネリックを扱う代わりに、フックは引数を受け取り、結果を返す単純な関数です。渡す必要があるのは、RootStateAppDispatchの型だけです。

標準のTypeScript設定と使用方法のガイドラインに従って、フックの「事前型付けされた」エイリアスを設定して、それらが正しい型を備えているようにし、アプリではそれらの事前型付けされたフックのみを使用することを具体的に説明しています。

まず、フックを設定します。

src/app/hooks.ts
import { useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, RootState } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()

次に、コンポーネントで使用します。

src/features/todos/TodoListItem.tsx
import { useAppSelector, useAppDispatch } from '../../app/hooks'
import {
todoToggled,
todoDeleted,
selectTodoById,
selectActiveTodoId
} from './todosSlice'

interface TodoListItemProps {
todoId: string
}

function TodoListItem({ todoId }: TodoListItemProps) {
// Use the pre-typed hooks in the component
const dispatch = useAppDispatch()
const activeTodoId = useAppSelector(selectActiveTodoId)
const todo = useAppSelector(state => selectTodoById(state, todoId))

// omit event handlers and rendering logic
}

詳細情報

詳細については、これらのドキュメントページとブログ投稿を参照してください。