LoginSignup
2
3

More than 3 years have passed since last update.

React Redux Hooks公式ドキュメント翻訳(useDispatch, useStore編)

Posted at

Reactアプリケーションの状態管理のためのOSSライブラリである、React Reduxのバージョン7.1.0で追加された、Hooks APIの公式ドキュメントを翻訳していきます。

  1. React Redux Hooks公式ドキュメント翻訳(概要編)
  2. React Redux Hooks公式ドキュメント翻訳(useSelector編)
  3. React Redux Hooks公式ドキュメント翻訳(useDispatch, useStore編)

2021/2/24公開。原文リンクは以下。
・公式ドキュメント(React Redux Hooks):https://react-redux.js.org/api/hooks

今回の記事はuseDispatchAPI, useStoreAPI編です。スクリーンショット 2021-02-23 23.57.03.png
スクリーンショット 2021-02-23 23.57.12.png

useDispatch()

const dispatch = useDispatch()

このhookAPIはRedux storeからdispatch関数を参照し、返り
値として返します。このAPIはアクションをdispatchしたい場合に使うと良いでしょう。

Note: ReactのuseReducerのようにdispatch関数の戻り値は同一であり、再
レンダリングされても不変です。(不変にならないケースとしては、Providerで設定したstoreを変更した場合に限ります。もっとも、そのような使い方は極めて稀ですが。)

使用例

import React from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const dispatch = useDispatch()

  return (
    <div>
      <span>{value}</span>
      <button onClick={() => dispatch({ type: 'increment-counter' })}>
        Increment counter
      </button>
    </div>
  )
}

覚えておいて欲しいこと: 子の関係にあるコンポーネントにdispatch関数を使ってcallbackをした際は、そのことをuseCallbackAPIを用いて記録する必要があります。通常、callbackを使用する際にcallback関数を宣言することと同じです。これによって、子の関係にあるコンポーネントの不必要なレンダリングを避けることができます。安全な方法としては、useCallbackAPIのための独立した[dispatch]配列を作成してあげることです。なぜなら、dispatch関数は不変だからです。こうすることでcallbackする際にその配列を適切に再使用してくれます。

使用例

import React, { useCallback } from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const dispatch = useDispatch()
  const incrementCounter = useCallback(
    () => dispatch({ type: 'increment-counter' }),
    [dispatch]
  )

  return (
    <div>
      <span>{value}</span>
      <MyIncrementButton onIncrement={incrementCounter} />
    </div>
  )
}

export const MyIncrementButton = React.memo(({ onIncrement }) => (
  <button onClick={onIncrement}>Increment counter</button>
))

useStore

const store = useStore()

このhookAPIはProviderコンポーネントで設定したものと同じRedux Storeを参照し、返り値として返します。このhookAPIは頻繁には使いません。useSelectorの方が頻繁につかうことになるでしょう。しかし、これは時々、特定のケースでstoreにアクセスする場合、役に立ちます。例えば以下のように、reducerをリプレイスするケースです。

使用例

import React from 'react'
import { useStore } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const store = useStore()

  // EXAMPLE ONLY! Do not do this in a real app.
  // The component will not automatically update if the store state changes
  return <div>{store.getState()}</div>
}
2
3
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
2
3