こんにちは!
今回は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,
dispatch
のaction.type
をスペルミスした状態で、EventForm
コンポーネントを呼び出すとどうなるか。
console上はエラーになりません。
Reducerの定義の部分で、action.type
のswitch
文で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,
エラーになりましたね。
予めaction.type
は変数で設定することをルール化しておくことで、エラーを検知しやすくなると思います。
参考文献
【udemy】React Hooks 入門 - Hooksと Redux を組み合わせて最新のフロントエンド状態管理手法を習得しよう!
https://www.udemy.com/course/react-hooks-101/
はむさん、ありがとうございます!