Chapter 3 · Practice 1 of 4
Use an effect only to sync with something outside React
Why it matters
An effect is an escape hatch for connecting to an external system: a browser API, a WebSocket, a third-party widget, a timer. It is not for transforming data for rendering or for reacting to a button click.
The React docs list the common misuses:
| You want to | Put it here, not in an effect |
|---|---|
| Compute derived data | In render |
| Respond to a click or submit | In the event handler |
| Reset state when a prop changes | A key |
| Subscribe to an external store | useSyncExternalStore |
Before writing useEffect, ask what external system you are syncing with. If you cannot name one, you probably do not need the effect. Removing unneeded effects also removes extra renders and timing bugs.
Do
- Put logic caused by a click or submit in that event handler
- Use
useSyncExternalStoreto subscribe to an external store
Avoid
- Chains of effects that set state to trigger other effects
- An effect that notifies the parent about a state change