React コンポーネントのレビューなどでよく引用するヤツ
他の state や props などから導出できる値を useState で管理しているとき
Think of state as the minimal set of changing data that your app needs to remember. The most important principle for structuring state is to keep it DRY (Don’t Repeat Yourself).
Can you compute it based on existing state or props in your component? If so, it definitely isn’t state!
code:quote
Think of state as the minimal set of changing data that your app needs to remember. The most important principle for structuring state is to keep it DRY (Don’t Repeat Yourself).
(snip)
Can you compute it based on existing state or props in your component? If so, it definitely isn’t state!
イベントハンドラに書くべきロジックを useEffect で書いているとき
You don’t need Effects to handle user events. For example, let’s say you want to send an /api/buy POST request and show a notification when the user buys a product. In the Buy button click event handler, you know exactly what happened. By the time an Effect runs, you don’t know what the user did (for example, which button was clicked). This is why you’ll usually handle user events in the corresponding event handlers.
データの加工のために useEffect を利用しているとき
You don’t need Effects to transform data for rendering. For example, let’s say you want to filter a list before displaying it. You might feel tempted to write an Effect that updates a state variable when the list changes. However, this is inefficient. When you update your component’s state, React will first call your component functions to calculate what should be on the screen. Then React will “commit” these changes to the DOM, updating the screen. Then React will run your Effects. If your Effect also immediately updates the state, this restarts the whole process from scratch! To avoid the unnecessary render passes, transform all the data at the top level of your components. That code will automatically re-run whenever your props or state change. 効果の薄い useMemo が多用されてコードが読みづらくなっているとき
"さすがに使わない場合はいつか" の箇所
const ageNum = useMemo(() => Number(age) || 0, [age]);
これはそもそもNumber(age) || 0が全然重くない計算なのでキャッシュする意味が無いこと、そしてオブジェクトを生成する計算ではないのでそちらの利点もありません。明らかに無駄です。
code:quote
"Should you add useMemo everywhere?" の箇所
setStatus な関数を依存配列に含めているとき
Note
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
コンポーネントの state のリセット