🤔
何でこんなコード書いたんだろう、これがワカラナイ
個人開発中にふと以前書いたコードを見ると、よくよく考えたらとても無駄なコードを書いているのに気づく事がある。なぜこんなコードを書いてしまったのだろう、と自分自身の過去の行動に首を傾げるばかりだ。
以下のコードは、修正前のコードである。わざわざ不要なuseEffectを使用して、周りくどい方法でボタンの状態管理(disabled)を行なっていた。
一部コードを改変
import { useAppContext } from "@/app/context/AppContext";
import { useEffect, useState } from "react";
import Image from "next/image";
import menuData from "@/app/config/config.json";
const EditorActionButton = ({ isApiLoading, difficulty, dataType, topic, uiLanguage, editorContent }) => {
const {
} = useAppContext();
// 選択肢が全て選択されたかどうかの状態管理に使用
const [isAllSelected, setIsAllSelected] = useState<boolean>(false);
const [isEditorInputedState, setIsEditorInputedState] =
useState<boolean>(true);
// 全ての選択肢が選択されたかどうかを判定する
useEffect(() => {
if (
difficulty !== "" &&
dataType !== "" &&
topic !== "" &&
uiLanguage !== ""
) {
setIsAllSelected(true);
} else {
setIsAllSelected(false);
}
}, [difficulty, dataType, topic, uiLanguage]);
useEffect(() => {
if (
isAllSelected === true &&
editorContent &&
editorContent?.length >= 1 &&
editorContent?.length <= 5000
) {
setIsEditorInputedState(false);
} else if (editorContent && editorContent?.length >= 5001) {
setIsEditorInputedState(true);
} else {
setIsEditorInputedState(true);
}
}, [isAllSelected, editorContent]);
// この部分を使用して、disabled={isButtonDisabled}と設定する
const isButtonDisabled =
isApiLoading ||
isEditorInputedState ||
(editorContent && editorContent?.length <= 0) ||
false;
return (
<button disabled={isButtonDisabled}>
Submit
</button>
こんな形で、以前はdifficultyやeditorContentの状態更新にuseEffectを使用していた。しかし、よく見ると何となく「この部分、状態管理とか使わなくても変数で直接disabledの判定を計算すれば良いのでは?」と感じた。
isButtonDisabled
の条件式も、わざわざ(editorContent && editorContent?.length <= 0) || false
と周りくどい記述もある。
これでは後にバグの温床や機能変更の際に、余計な時間が掛かると思った。
以下は、変数に置き換えた場合のコードである。
const isAllSelected = difficulty !== "" && dataType !== "" && topic !== "" && uiLanguage !== "";
const isEditorInputedState =
!isAllSelected ||
!editorContent ||
editorContent.length < 1 ||
editorContent.length > 5000;
const isButtonDisabled = isApiLoading || isEditorInputedState;
上記のようにuseEffect
を削除し、変数で直接管理することで、以下の利点を得られる。
- 不要なレンダリングを防ぎ、パフォーマンスを向上
- 状態の管理がシンプルになり、コードの可読性が向上
このような冗長なコードは、まだプロジェクト内に多く残っている可能性があるため、折を見て少しずつ改善していきたい。
Discussion