Custom Hooks Patterns

Medium•

Title says patterns, so categorize patterns explicitly. Strong answers compare when to use each, where abstractions leak, and how debugging complexity changes.

Quick Decision Guide

Custom hooks are behavior modules for React, but pattern choice matters.

Core pattern families: - stateful utility hooks - resource/subscription hooks - orchestration hooks (workflow/state machine)

Interview signal: explain which pattern you chose and why.

Pattern Categories (Title-Intent Coverage)

🔥 Insight

A custom hook is a contract. Different problem shapes need different hook patterns.

Pattern 1: Stateful Utility Hook

•Example: useDebouncedValue, useToggle
•Best for local behavior without external IO

Pattern 2: Resource / Subscription Hook

•Example: useResizeObserver, useSocketSubscription
•Owns setup/cleanup and external lifecycle

Pattern 3: Orchestration Hook

•Example: useCheckoutFlow, useSearchController
•Coordinates multiple states/effects and exposes intent-level actions

How It Works, Trade-offs, and Failure Modes

function useDebouncedValue(value, delay) {
  const [debounced, setDebounced] = useState(value)
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay)
    return () => clearTimeout(id)
  }, [value, delay])
  return debounced
}

Trade-offs

•Better reuse and testability
•Hidden coupling if hook API is broad or ambiguous
•Harder debugging when hooks nest deeply without clear ownership

Where abstraction breaks down

•Hook returns too many unrelated values/actions
•Hook swallows errors/retry semantics and hides failure behavior

Rules of Hooks (and why)

•Call hooks at the top level of React components or custom hooks.
•Do not call hooks inside conditions, loops, or nested functions.
•Only call hooks from React function components or other custom hooks.

These rules follow from React's render model:

•React relies on consistent hook call order across renders.
•Hook identity is tied to position in the render sequence.
•Conditional or reordered hook calls can misassociate state/effects and produce incorrect behavior.

Common Misuse Patterns and Interview Takeaway

Common Mistakes

•Mixing unrelated concerns in one catch-all hook
•No cancellation/cleanup for asynchronous work
•Leaking implementation details through unstable API shape

🎯 Interview Takeaway

Name the pattern, state ownership, lifecycle boundaries, and how consumers reason about failure/retry.

Key Takeaways

1Pattern choice should match problem shape.
2Custom hook APIs are contracts: keep them focused and stable.
3Lifecycle ownership and cleanup semantics are non-negotiable.
4Interview answers should classify pattern + trade-offs, not just show syntax.