ReactにおけるuseEffectの使い方
これの続き
基本的にはcomponentDidMount / componentDidUpdateで書く内容をuseEffectに書けばよいはず
you might not need an effect
Effects are an escape hatch from the React paradigm. They let you “step outside” of React and synchronize your components with some external system like a non-React widget, network, or the browser DOM.
EffectsはReactno外部コンポーネントとつなぐためのものだよ
If there is no external system involved (for example, if you want to update a component’s state when some props or state change), you shouldn’t need an Effect.
もしReact内で完結する依存であれば、Effectはいらないはず
e.g.
You don’t need Effects to transform data for rendering.
You don’t need Effects to handle user events.
Removing unnecessary Effects will make your code easier to follow, faster to run, and less error-prone.
不必要なEffectは除いた方がいい
You do need Effects to synchronize with external systems.
外部と同期的にsyncする場合は、必ずEffectを使わなければならない
useEffect ベストプラクティス
state / callbackで表現せず、rendering内で状態を確定させる
When something can be calculated from the existing props or state, don’t put it in state. Instead, calculate it during rendering.
Avoid redundant state
If you can calculate some information from the component’s props or its existing state variables during rendering, you should not put that information into that component’s state.
React componentの外でpureに関数定義を行う
React componentの中でstate等依存するとどんどん複雑になっていく。
シンプルにcomponentの外でpureな関数定義を行ったほうが良い。