Skip to the page

Component patterns · mid

Designing custom hooks

A custom hook is a function starting with use that calls other hooks to share stateful logic (not state itself); a good one has a clear input/output contract, stable returned functions, and full cleanup.

The notes

What you must know

  • Hooks share logic, not state: two components calling useCounter() get two separate counters.
  • Name starts with use so the linter applies the rules of hooks.
  • Contract: inputs (arguments), outputs (object for many named values, tuple for 2 values like useState), and documented behaviour on input change.
  • Return stable callbacks (useCallback) when callers may put them in deps or pass them to memoized children (or rely on the React Compiler).
  • Clean up everything: timers, listeners, subscriptions, in-flight requests (abort/ignore).
  • useDebouncedValue(value, delay): keep debounced state, set a timeout in an effect on [value, delay], clear it in cleanup.
  • useFetch(url): status/data/error state, ignore or abort on url change and unmount. If you start adding caching, dedupe and retries, use TanStack Query or RTK Query instead.
  • Test hooks with renderHook from React Testing Library (see the testing track).

The red pen

Common traps: mistake → fix

  • Mistake: "Two components using the same hook share its state"

    Fix: each call has its own state; share through context or a store.

  • Mistake: "Create the debounced function directly in render"

    Fix: a new debounced function every render loses the timer.

  • Mistake: "A custom hook is just a utility function"

    Fix: if it calls hooks, it must follow the rules of hooks.

Easy to hard

Questions interviewers ask, easy to hard

  1. Write a useDebouncedValue hook.
  2. Write a useFetch(url) hook. Make it abort on unmount or URL change.
  3. Tuple or object return: which and why?
  4. At what point do you stop and use TanStack Query?
  5. How do you test a custom hook?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview