Reviewer · React
Hook design discipline
Design custom hooks with a single, clear responsibility and stable outputs: 1. **Keep dependency references stable.** When a hook returns an object (e.g. a mutation object from a data-fetching library), it may be re-created on every render even if its contents are logically unchanged. Depend on the stable function/value inside it (e.g. `mutateAsync`)...
Design custom hooks with a single, clear responsibility and stable outputs:
- Keep dependency references stable. When a hook returns an object (e.g. a mutation object from a data-fetching library), it may be re-created on every render even if its contents are logically unchanged. Depend on the stable function/value inside it (e.g.
mutateAsync) rather than the whole object inuseCallback/useMemodependency arrays, to avoid cascading re-renders through every derived callback.
// Avoid: new object identity each render destabilizes dependents
const requestEdits = useCallback(() => applyDataStreamEditsMutation.mutateAsync(...), [applyDataStreamEditsMutation]);
// Prefer: depend on the stable function
const { mutateAsync } = applyDataStreamEditsMutation;
const requestEdits = useCallback(() => mutateAsync(...), [mutateAsync]);
-
Don’t let hooks mix concerns. A hook that exposes server/source-of-truth state (e.g.
useConversationPermissions) should keep returning exactly what that source says. UI-only decisions (e.g. hiding a button for a specific conversation type) belong in the component, applied with the same condition used elsewhere, not baked into the “truth” hook. -
Avoid hook sprawl. When a feature accumulates many small, overlapping hooks/helpers (e.g.
isThread,isThreadConversation,useIsThread,useThreadParent,useOpenThread), consolidate related ones into a single module/hook before building more UI on top. Fewer, well-scoped hooks are easier to reason about and test. -
Fix shared hook bugs at the source. If a shared hook has a gap (e.g.
useDataViewstayingpristineon error) and multiple consumers independently work around it, propagate the fix in the shared hook itself rather than duplicating the workaround, so all current and future consumers benefit.