0
1

More than 3 years have passed since last update.

useReducerの処理の流れ

Posted at

学習の備忘録として残しています。

データをコンポーネントが受け取ってブラウザに表示するための方法としてReact Hooksを使用し、コンポーネントにstateを注入する方法がある。
useStateとuseReducerの2つ。

useReducerを使う場面

複数の値にまたがる複雑なstateロジックがある場合や
前のstateに基づいて次のstateを決める必要のある場合。

処理の流れ

全体像

jsx

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

この場合、
Counterコンポーネント内の一行目でuseReducerが定義されている。
簡単に解釈すると、stateはinitialState,actionがdispatchに該当する。

jsx
return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>

この中のdispatchで、reducerの関数を呼び出して、stateがセットされる。
dispatchの引数は1つで、慣習としてtypeをキーにもつ値を入力する。
もし、dispatchの引数が{type: 'decrement' なら

jsx
case 'decrement':
      return {count: state.count - 1};

この部分が読み込まれ、stateのcountが1下がる。
そのため

jsx
Count: {state.count}

の返り値は-1となる。

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