6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

前回に引き続き、Udemyの教材を見ながら勉強していて自分なりの復習用に記事を残しています。

useReducerとは

多くのイベントハンドラにまたがって state の更新コードが含まれるコンポーネントは、理解が大変になりがちです。このような場合、コンポーネントの外部に、リデューサ (reducer) と呼ばれる単一の関数を作成し、すべての state 更新ロジックを集約することができます。

出典: state ロジックをリデューサに抽出する
定義されたstateとロジックを一つのhooksにまとめて一元管理できるという事でしょうか。
具体的にはどういう事かuseStateと比べながら見ていきます。

useStateのおさらい

まずuseStateは、ユーザ操作の結果として画面上の表示内容を変更する様な場合の時に、変更した値をどこかに保持する事を可能にするhooksになります。
例えば、ネットで買い物する時に購入ボタンを押したり、購入する商品の点数を変更したりした時の現在の入力値を保持します。
以下、簡単な例をコードに書きました。

index.js
import {useState} from "react"

const initialState = {
  count: 0
}

export const Example = () => {
  const [state, setState] = useState(initialState)
  const incrementClick = () => {
    setState({count: state.count + 1})
  }

  const decrementClick = () => {
    setState({count: state.count - 1})
  }

  return (
    <>
      <p>数値は: {state.count}</p>
      <button onClick={incrementClick}>プラス</button>
      <button onClick={decrementClick}>マイナス</button>
    </>
  )
}

Reactを学んだことがあるなら、誰でも知っている様なコードですね。
全く同じ内容をuseReducerで書いてみたいと思います。

index.js
import {useReducer} from "react"

const initialState = {
  count: 0
}

const reducer = (state, action) => {
  switch (action.type) {
    case "incremented":
      return {...state, count: state.count + 1}
    case "decremented":
      return {...state, count: state.count - 1}
    default:
      throw new Error("Error")
  }
}

export const Example = () => {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <>
      <p>数値は: {state.count}</p>
      <button
        onClick={() => {
          dispatch({type: "incremented"})
        }}
      >
        プラス
      </button>
      <br />
      <button
        onClick={() => {
          dispatch({type: "decremented"})
        }}
      >
        マイナス
      </button>
    </>
  )
}   

初期値のオブジェクトまではuseStateと一緒ですが、useReducerではreducer関数を作成しaction.typeによって数値をプラスするかマイナスにするかを分けています。
プラスボタンを押下したらdispatchでreducer関数を発火させます。
プラスボタンのtypeが "incremented"なので return {...state, count: state.count + 1}が実行され数値がプラス1されます。
マイナスボタンも同様でdispatchでreducer関数を発火させて、マイナスボタンのtypeが "decremented"なので {...state, count: state.count - 1} が実行され数値がマイナス1になります。
これだとあまりuseReducerのメリットが分からないかと思うので、以下のyoutubeの動画の様に3つのuseStateを1つにまとめたりすることも可能の様です。

(こんなことが出来るのか…と閲覧しながら思いました)
まだ個人的に知識が定着しているとは言い難いので、実務でも積極的に使ったり小さなアプリとか作って一つ一つ覚えていきたいと思います。
Reactに限らずですが、プログラミングは奥が深い…:disappointed_relieved:

参考になった記事

6
0
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
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?