フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

React ReduxからHooksAPIが利用できる(ver7.1)

はじめに

useDispatch

  • Reduxストアからディスパッチ関数への参照を返します。必要に応じて、アクションをディスパッチするために使用できます。
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>
  )
}

useStore

  • コンポーネントに渡されたものと同じReduxストアへの参照を返します。 このフックはおそらく頻繁に使用すべきではありません。主な選択肢としてuseSelector()をお勧めします。ただし、これは、レデューサーの交換など、ストアへのアクセスを必要とするあまり一般的でないシナリオでは役立つ場合があります。
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>
}

useSelector

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

export const CounterComponent = () => {
  const counter = useSelector(state => state.counter)
  return <div>{counter}</div>
}

パフォーマンス

総評

  • 便利でよさそうですが、パフォーマンスは少し懸念があるようです