Building Custom React Hooks: Patterns from 90+ Projects
Custom hooks are the most powerful abstraction React offers. After extracting and refining hooks across 90+ projects, I've identified the patterns that consistently reduce code duplication, improve testability, and make components dramatically cleaner.
The Golden Rule of Custom Hooks
Before extracting a hook, ask: "Does this logic need to be shared, or am I just moving complexity?" A hook that's used once is just indirection. Extract when you see the same stateful pattern in 2+ components.
Pattern 1: useAsync — The Universal Data Fetcher
Every project needs a hook that handles the loading → data → error lifecycle. Instead of writing useState trios in every component:
- Tracks
loading,data,error, andexecutefunction - Supports immediate execution or deferred (triggered by user action)
- Handles race conditions via abort controller — if the component unmounts or a new request starts, the old one is cancelled
- Returns a
resetfunction to clear state
This single hook replaced 200+ lines of duplicated fetch logic across one enterprise dashboard.
Pattern 2: useDebounce — Controlled Input Delays
Search inputs, auto-save fields, and resize handlers all need debouncing. The hook accepts a value and delay, returns the debounced value, and cleans up the timeout on unmount. Combined with useEffect watching the debounced value, it's a clean pattern for search-as-you-type.
Performance impact: reduced API calls on a product search page from ~40/minute to ~8/minute per user — a 5x reduction in backend load.
Pattern 3: useLocalStorage — Persistent State
A drop-in replacement for useState that syncs to localStorage. Key implementation details that most tutorials miss:
- Use
JSON.parse/JSON.stringifywith try-catch for corrupt data - Support a
serializer/deserializeroption for custom types - Listen to
storageevents for cross-tab synchronization - Lazy initialization — only read from localStorage on mount, not every render
Pattern 4: useMediaQuery — Responsive Logic
CSS handles responsive styling, but sometimes you need responsive logic — rendering different components, changing data fetch parameters, or altering animation behavior based on viewport. This hook wraps window.matchMedia with proper cleanup and SSR safety (returns false during server render).
Pattern 5: useClickOutside — Modal/Dropdown Dismissal
Every dropdown, popover, and modal needs "click outside to close" behavior. The hook accepts a ref and a callback, attaches a document-level click listener, and checks if the click target is outside the ref's element. Key detail: use mousedown instead of click to catch the event before the element potentially unmounts.
Pattern 6: useIntersectionObserver — Lazy Loading & Analytics
Wraps the Intersection Observer API for use cases like infinite scroll, lazy image loading, and scroll-based analytics. Returns isIntersecting and the full IntersectionObserverEntry. We use this to track which blog sections users actually read — the data drove our content strategy for a year.
Testing Custom Hooks
Use @testing-library/react-hooks (or renderHook from RTL 14+). The key principle: test the hook's behavior through its return values and effects, not its implementation. Mock external dependencies (fetch, localStorage, timers) at the boundary.
Hook Composition
The real power emerges when hooks compose. useSearchParams can use useDebounce internally. useInfiniteScroll composes useIntersectionObserver with useAsync. Each hook stays focused and testable while the composition handles complexity.
Need help building a custom hooks library for your team? Let's discuss the patterns that fit your stack.