🙆
ReactやTypescriptのモダンでスマートな書き方(随時更新)
概要
冗長な書き方が多いので備忘のために、モダンでスマートな書き方を残しています。
随時記載していきますが、この書き方はダサい!危険!などありましたらコメントで教えていただけますと幸いです。
refオブジェクトのnull判定
before
const ref = useRef<HTMLDivElement | null>(null)
if (ref === null || ref.current === null) return
after
const ref = useRef<HTMLDivElement | null>(null)
if (!ref?.current) return
複数のor条件(左辺が同じ場合)
before
if (val === 'aaa' || val === 'bbb' || val === 'ccc') return
after①
if (['aaa', 'bbb', 'ccc'].includes(val)) return
after②
const validValues = new Set(['aaa', 'bbb', 'ccc']);
if (validValues.has(val)) return
after③
switch (val) {
case 'aaa':
case 'bbb':
case 'ccc':
break;
}
使い分け
| 方法 | 読みやすさ | パフォーマンス | 使い所 |
|---|---|---|---|
| includes | ⭐⭐⭐ | 普通 | 数個の値(おすすめ) |
| Set.has | ⭐⭐ | 高速 | 多数の値、繰り返し使用 |
| switch | ⭐⭐ | 普通 | 各caseで異なる処理 |
Discussion