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

useReducerを使ってみた

Posted at

はじめに

ReactでuseReducerを使ってみました。React歴、フロント歴ともに1年半位なのですが、useReducerを触った事がありませんでした。ビジネスロジックが複雑になるにつれて、useStateでやり切るのは難しいなと感じ、今回useReducerを触ってみることにしました。

成果物

counter.gif

ソースコード

Counter.tsx(useReducer利用)
import React, { useReducer } from 'react';
import { Action, State } from './type';

// reducer関数を定義
const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

const Counter: React.FC = () => {
  // useReducerを使って状態を管理
  const [state, dispatch] = useReducer(reducer, { count: 0 });

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

export default Counter;

→これで動きます。ただ、useStateを使う場合、下記で書けます。

Counter.tsx(useState利用)
import React, { useState } from 'react';

const Counter: React.FC = () => {
  // useStateを使って状態を管理
  const [count, setCount] = useState(0);

  return (
    <div>
      Count: {count}
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
};

export default Counter;

→これで動きます。

useReducerの使いどころ

useReducerはuseStateより書くコード量が増えるため、シンプルな処理の場合はuseStateで良いかな。ただ、stateの特定値による処理変更、イベント情報により処理が変更される等のビジネスロジックが変わる時に使うのがいい気がします。

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