React Best Practices

Chapter 3 · Practice 1 of 4

Use an effect only to sync with something outside React

From Effects, and when you do not need one

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 toPut it here, not in an effect
Compute derived dataIn render
Respond to a click or submitIn the event handler
Reset state when a prop changesA key
Subscribe to an external storeuseSyncExternalStore

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 useSyncExternalStore to 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