LoginSignup
2
1

More than 3 years have passed since last update.

【React Hooks】useReducerを使う時、dispatchのtypeには変数で与えた方がいい理由

Last updated at Posted at 2020-08-20

こんにちは!

今回はReact Hooksについてお伝えしたいと思います。
中でも、「useReducerを使う時、dispatchのaction.typeには変数で与えた方がいい理由」について触れていきます。

dispatchのaction.typeをハードコーディングすると、エラーにきづかない!?

※useReducerに絡む部分以外は省略して書いています。

const [state, dispatch] = useReducer(reducer, initialState);

// Reducer
const reducer = (state = [], action) => {
    switch(action.type) {
        // action.type : 'CREATE_EVENT'
        case CREATE_EVENT:
            const event = {title: action.title, body: action.body};
            const length = state.length;
            let id;
            if (length === 0) {
                id = 1;
            } else {
                id = state[length - 1].id + 1;
            }
            return [...state, {id: id, ...event}];
        default:
            return state;
    }
}

const EventForm = () => {
    const initialState = {
        events: [],
    };

    // Reducerを呼び出す
    const [state, dispatch] = useReducer(reducer, initialState);

    // dispatchを呼び出す
    const addButtonClickEvent = () => {
        dispatch({
          type: 'CREATE_EV', // <-スペルミスしたとします
          title,
          body,

dispatchaction.typeをスペルミスした状態で、EventFormコンポーネントを呼び出すとどうなるか。
image.png

console上はエラーになりません。
Reducerの定義の部分で、action.typeswitch文でdefaultの場合何もしないと定義しているためです。
しかし、このままですと、エラーに気づかないので、バグ対応にコストを要してしまいます。

dispatchのtype名は変数で与えると、どうなるか?



// actionのtype名は一箇所で定義し、各ファイルで読み込む
// const CREATE_EVENT = 'CREATE_EVENT';
import {CREATE_EVENT} from '../actions/index';

// ・・・・(省略)

    // dispatchを呼び出す
    const addButtonClickEvent = () => {
        dispatch({
          type: CREATE_EVE, // <-スペルミスしたとします
          title,
          body,

結果は・・・
image.png

エラーになりましたね。
予めaction.typeは変数で設定することをルール化しておくことで、エラーを検知しやすくなると思います。

参考文献

【udemy】React Hooks 入門 - Hooksと Redux を組み合わせて最新のフロントエンド状態管理手法を習得しよう!
https://www.udemy.com/course/react-hooks-101/
はむさん、ありがとうございます!

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