Awesome Reviewers

Reviewer · React

Avoid unnecessary effects

Reserve `useEffect` for synchronizing with truly external/imperative systems (DOM APIs, subscriptions, measuring/scrolling a ref-based widget); don't use it to compute values that are derivable from existing props/state. When a value depends only on render-time inputs, compute it directly during render (optionally memoized), or update it synchronously...

Instruction

Reserve useEffect for synchronizing with truly external/imperative systems (DOM APIs, subscriptions, measuring/scrolling a ref-based widget); don’t use it to compute values that are derivable from existing props/state. When a value depends only on render-time inputs, compute it directly during render (optionally memoized), or update it synchronously during render using the “store previous props/state and compare” pattern — not by writing to a ref during render (refs mutated in render are unsafe) and not by scheduling it in an effect, since effects run after paint and can let the browser show one frame of stale UI (cascading-render-via-effect is worse than a same-render state update, which React applies before painting).

Example of the preferred render-time pattern instead of an effect:

const [prevItems, setPrevItems] = useState(items);
if (prevItems !== items) {
  setPrevItems(items);
  setSelectedIndex(items.length > 0 ? 0 : null);
}

When the derived computation is expensive (e.g. searching/filtering a large tree), keep the input update synchronous but defer the expensive derivation with useDeferredValue/startTransition so typing/input handling is never blocked; expose a pending flag (value !== deferredValue) to show a loading indicator if the computation is non-trivial. Prefer batching related state changes into the same setter/event handler (rather than multiple separate useEffects reacting to each other) to avoid extra render passes. When an effect does need to subscribe to an external event (e.g. a keydown listener), keep its dependency list minimal — extract any logic that depends on frequently-changing state into useEffectEvent so the subscription isn’t torn down and recreated on every state change. Before adding any effect, ask whether the same result could be achieved during render, in an event handler, or in a memoized value — only fall back to an effect when none of those apply.