メインコンテンツへスキップ

React Redux 入門

React Redux は、React 用の公式 UI バインディングレイヤーであり、Redux 用のものです。これにより、React コンポーネントは Redux ストアからデータを読み取り、ストアにアクションをディスパッチして状態を更新できます。

インストール

React Redux 8.x では、React Hooks を使用するために、React 16.8.3 以降 / React Native 0.59 以降が必要です。

React Redux アプリの作成

React と Redux を使用して新しいアプリを開始する推奨方法は、Vite 用の公式 Redux+TS テンプレートを使用するか、Next の with-redux テンプレートを使用して新しい Next.js プロジェクトを作成することです。

どちらも、そのビルドツールに合わせて Redux Toolkit と React-Redux が適切に構成されており、Redux Toolkit のいくつかの機能の使用方法を示す小さなサンプルアプリが付属しています。

# Vite with our Redux+TS template
# (using the `degit` tool to clone and extract the template)
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app

# Next.js using the `with-redux` template
npx create-next-app --example with-redux my-app

現在、公式の React Native テンプレートはありませんが、標準の React Native および Expo 用にこれらのテンプレートをお勧めします。

既存の React アプリ

React Redux を React アプリで使用するには、依存関係としてインストールします

# If you use npm:
npm install react-redux

# Or if you use Yarn:
yarn add react-redux

また、Redux をインストールし、アプリでRedux ストアをセットアップする必要があります。

React-Redux v8 は TypeScript で記述されているため、すべての型が自動的に含まれます。

API の概要

Provider

React Redux には <Provider /> コンポーネントが含まれており、これにより Redux ストアがアプリの他の部分で利用できるようになります

import React from 'react'
import ReactDOM from 'react-dom/client'

import { Provider } from 'react-redux'
import store from './store'

import App from './App'

// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<Provider store={store}>
<App />
</Provider>,
)

フック

React Redux は、React コンポーネントが Redux ストアと対話できるようにするカスタム React フックのペアを提供します。

useSelector はストアの状態から値を読み取り、更新をサブスクライブしますが、useDispatch はストアの dispatch メソッドを返して、アクションをディスパッチできるようにします。

import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
decrement,
increment,
incrementByAmount,
incrementAsync,
selectCount,
} from './counterSlice'
import styles from './Counter.module.css'

export function Counter() {
const count = useSelector(selectCount)
const dispatch = useDispatch()

return (
<div>
<div className={styles.row}>
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
+
</button>
<span className={styles.value}>{count}</span>
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
-
</button>
</div>
{/* omit additional rendering output here */}
</div>
)
}

React Redux の学習

現代の Redux ライブストリームを学ぶ

Redux メンテナーの Mark Erikson が「Learn with Jason」ショーに出演し、今日 Redux を使用する推奨方法を説明しました。このショーには、Redux Toolkit と React-Redux フックを Typescript で使用する方法、および新しい RTK Query データフェッチ API を示すライブコードのサンプルアプリが含まれています。

トランスクリプトとサンプルアプリのソースへのリンクについては、「現代の Redux を学ぶ」ショーのノートページを参照してください。

ヘルプとディスカッション

#redux チャンネルは、Reactiflux Discord コミュニティの Redux の学習と使用に関するすべての質問に対する公式リソースです。Reactiflux は、たむろし、質問し、学ぶのに最適な場所です。ぜひご参加ください!

#redux タグを使用して、Stack Overflow で質問することもできます。

ドキュメントの翻訳