HomeReact
Chapter 12

12 β€” Custom Hooks

Custom hooks let you extract and reuse stateful logic across components. A custom hook is just a function that calls other hooks.

Rules

  1. Name must start with use β€” useToggle, useFetch, useDebounce
  2. Can call any hook inside (useState, useEffect, other custom hooks)
  3. Each component using the hook gets its own independent state
  4. Return whatever the consumer needs: value, setter, object, tuple

Why Custom Hooks?

WithoutWith Custom Hook
Duplicate state + effect logic in 5 componentsWrite once, import everywhere
40 lines of fetch/loading/error in each componentconst { data, loading } = useFetch(url)
Complex cleanup logic repeatedEncapsulated in the hook

Common Custom Hooks

HookPurpose
useToggleBoolean toggle state
useFetchData fetching with loading/error
useDebounceDebounce a value
useLocalStorageSync state with localStorage
useMediaQueryResponsive breakpoint detection
useOnClickOutsideDetect clicks outside an element
useIntersectionObserverLazy loading, infinite scroll
usePreviousTrack previous value

File

  • custom-hooks.tsx β€” 10+ production-ready custom hooks with TypeScript, examples, and usage patterns