Lesson 5 of 9 · 22m
Typed Custom Hooks That Age Well
Design hook inputs and returns as stable contracts, preserve generics through the boundary, and avoid object shapes that mutate every render.
A custom hook is an API wearing a React costume. Teams get into trouble when they treat hooks as junk drawers for reusable logic: inputs multiply, return objects churn every render, and TypeScript quietly widens everything into mush.
Name the state machine, not the implementation
type AsyncResource<T> =
| { status: "loading" }
| { status: "error"; error: Error }
| { status: "success"; data: T };A hook that returns this union is honest about what a consumer can render. Compare that with:
// weak: every combination is legal
{ data?: T; error?: Error; loading?: boolean }The weak shape makes every consumer perform the same awkward reconciliation. The union makes the hook do the modeling once.
Preserve generics through the hook
function useAsyncResource<T>(key: string, load: () => Promise<T>): AsyncResource<T> {
const [state, setState] = useState<AsyncResource<T>>({ status: "loading" });
useEffect(() => {
let active = true;
setState({ status: "loading" });
load().then(
(data) => active && setState({ status: "success", data }),
(error) => active && setState({ status: "error", error }),
);
return () => {
active = false;
};
}, [key, load]);
return state;
}The generic T enters through load and exits in data. If the caller loads a User, the consumer receives a User, not unknown and definitely not any.
Return objects should be stable or intentionally cheap
Hooks that return fresh objects are normal; hooks that return unstable callbacks cause memoization pain. Stabilize only when the churn is proven harmful:
const retry = useCallback(() => {
setState({ status: "loading" });
void load();
}, [load]);Do not memorize a rule like "wrap everything in useCallback." Measure first. Extra memoization is code too, and wrong dependencies are worse than no memoization.
Options objects beat parameter creep
type UseDebouncedValueOptions = {
delayMs?: number;
leading?: boolean;
};
function useDebouncedValue<T>(value: T, options: UseDebouncedValueOptions = {}) {
// ...
}An options object gives callers named arguments, keeps old call sites source-compatible when options are added, and documents itself better than four positional booleans ever will.
Field notes
- Hooks returning tuples (
as const) can be ergonomic, but objects are easier to extend without breaking destructuring order. - If a hook accepts a callback, decide whether referential instability should retrigger work; document the choice in behavior.
- Prefix internal cleanup flags with boring names like
active; clever cancellation abstractions often obscure simple races. - Test the type behavior too: a hook that compiles but returns
anyis still broken.
Was this lesson helpful?