Effects are for synchronizing with an external system: the network, a browser API, a non-React widget. When an effect only reads React state and sets other React state, it's usually in the wrong place.
The common cases:
- Derived values. A filtered list or a full name computed in an effect and stored in state renders once with the stale value, commits, then renders again. Compute it during render; wrap an expensive calculation in
useMemo. - Resetting state when a prop changes. Instead of
useEffect(() => setComment(''), [userId]), render the component withkey={userId}so React gives it fresh state. To adjust only part of the state, store an id and derive the rest. - Event-specific logic. A POST on submit, a toast after "Buy": they happen because of a click, so they belong in that handler. In an effect they also fire on remount, and twice in development.
- Chains of effects. Effects that set state to trigger other effects re-render the tree once per link. Compute all the next state in the handler, and derive what you can.
- Notifying a parent. Calling
onChangefrom an effect runs after the child already committed, so the parent renders in a second pass. Call it in the same handler as the child's ownsetState; React batches both. Or lift the state up. - Initialization once per app load: module level, not an effect.
- Subscribing to an external store:
useSyncExternalStore, rather than an effect that copies values into state.
Data fetching is synchronization, so it can be an effect, with cleanup for races. Frameworks and caching libraries, or use with a cached promise, do it better.
In eslint-plugin-react-hooks 7, the recommended react-hooks/set-state-in-effect rule flags the most common form: a setter called synchronously in an effect body.