intermediate

Custom hooks

Extract reusable stateful behavior while keeping render rules, dependencies, and ownership clear.

A custom hook is a function whose name starts with `use` and that may call other hooks. It extracts reusable stateful logic — data fetching, form fields, media queries — without changing the component tree. The hook owns the logic; components own the rendered output.

Share contracts through return values and arguments, not hidden module singletons. Test hooks with `@testing-library/react` render helpers or dedicated hook test utilities. Custom hooks must obey the rules of hooks: only call them at the top level of React functions.

On interviews, explain the concept with a concrete example and name the behavior interviewers probe.

Common pitfalls include hiding data flow, over-splitting components, and putting side effects in render.

The trade-off is often clarity versus reuse or explicit props versus convenience.

Checklist:

  • Prefix with `use` and follow hook rules.
  • Return stable, documented API surface.
  • Keep side effects inside the hook deliberate.