← Lessons

quiz vs the machine

Silver1120

Frontend

The Custom Hook Pattern

Extract stateful logic into a reusable function so components stay focused on rendering.

4 min read · intro · beat Silver to climb

Sharing logic, not state

A custom hook is just a function whose name starts with use and that calls other hooks. It packages stateful behavior, such as a timer or a data fetch, so many components can reuse the logic without copying it. Crucially each component that calls the hook gets its own independent state.

  • It bundles related state and effects together.
  • It returns values and updater functions to the caller.
  • Each call site holds a separate copy of the state.

Rules that keep it safe

A custom hook must follow the rules of hooks. Call it at the top level of a component or another hook, never inside a condition or loop, so the order of hook calls stays stable across renders.

  • Prefix the name with use so tooling recognizes it.
  • Call hooks unconditionally at the top level.
  • Return a small, clear interface to the component.

Custom hooks turn duplicated logic into a tested, named building block.

Key idea

A custom hook is a use prefixed function that bundles stateful logic for reuse, giving each caller its own independent state.

Check yourself

Answer to earn rating on the learn ladder.

1. What does each component get when it calls the same custom hook?

2. Where must a custom hook be called?