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
- Name must start with
useβuseToggle,useFetch,useDebounce - Can call any hook inside (useState, useEffect, other custom hooks)
- Each component using the hook gets its own independent state
- Return whatever the consumer needs: value, setter, object, tuple
Why Custom Hooks?
| Without | With Custom Hook |
|---|---|
| Duplicate state + effect logic in 5 components | Write once, import everywhere |
| 40 lines of fetch/loading/error in each component | const { data, loading } = useFetch(url) |
| Complex cleanup logic repeated | Encapsulated in the hook |
Common Custom Hooks
| Hook | Purpose |
|---|---|
useToggle | Boolean toggle state |
useFetch | Data fetching with loading/error |
useDebounce | Debounce a value |
useLocalStorage | Sync state with localStorage |
useMediaQuery | Responsive breakpoint detection |
useOnClickOutside | Detect clicks outside an element |
useIntersectionObserver | Lazy loading, infinite scroll |
usePrevious | Track previous value |
File
custom-hooks.tsxβ 10+ production-ready custom hooks with TypeScript, examples, and usage patterns