Open3

ReactにおけるuseEffectの使い方

ShigeShige

you might not need an effect

https://react.dev/learn/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を使わなければならない

ShigeShige

useEffect ベストプラクティス

state / callbackで表現せず、rendering内で状態を確定させる

https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state

When something can be calculated from the existing props or state, don’t put it in state. Instead, calculate it during rendering.

https://react.dev/learn/choosing-the-state-structure#avoid-redundant-state

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に関数定義を行う

https://qiita.com/keiya01/items/fc5c725fed1ec53c24c5#propsやstateに依存しない関数を使用する

React componentの中でstate等依存するとどんどん複雑になっていく。
シンプルにcomponentの外でpureな関数定義を行ったほうが良い。