React Custom Hook Patterns: Mastering Headless Architecture
Custom Hooks Patterns: Encapsulate and share stateful business logic cleanly across features.
In a clean React codebase, components should do one job well: render user interfaces. When components are forced to coordinate complex business rules, manage multi-step timers, or wire up browser APIs directly, they balloon into unmaintainable files that are painful to unit test and difficult to reuse.
Custom hooks are React's primary mechanism for abstracting and sharing stateful logic. At its core, a custom hook is a JavaScript/TypeScript function whose name starts with use and can call other hooks (useState, useEffect, useRef, etc.).
- **Crucial mental model:** Custom hooks share stateful logic, not state itself. Each component calling a custom hook gets its own isolated, private instance of that internal state.
## 1. The Headless Architecture Mindset
```text
The headless pattern separates behavior, state machines, and accessibility from visual presentation. By keeping DOM markup and styles decoupled from mechanics, your component styling remains unconstrained across platforms and design systems.
┌────────────────────────────────────────────────────────┐
│ CUSTOM HOOK (Headless Logic) │
│ • Manages state transitions (open/close, active index)│
│ • Listens to keyboard inputs (Escape, ArrowDown) │
│ • Injects ARIA contracts (aria-expanded, controls) │
└───────────────────────────┬────────────────────────────┘
│
Exposes clean contracts & state
│
┌──────────────────┴──────────────────┐
▼ ▼
┌────────────────────────┐ ┌────────────────────────┐
│ Tailwind Component │ │ Custom Radix / CSS-in-JS│
│ (Mobile Sheet/Drawer)│ │ (Desktop Dropdown) │
└────────────────────────┘ └────────────────────────┘
```
### Three Hallmarks of a Well-Designed Hook
- **Single Responsibility:** It solves one concrete problem well (e.g., observing element intersections, throttling a stream, or detecting viewport breakpoints).
- **Predictable API Contract:** Returns a concise tuple ([value, setter]) for simple two-element primitives, or a well-typed object (\{ data, isLoading, ref, actions \}) for feature sets with multiple handles.
- **Automatic Teardown Safety:** It cleans up after itself—cancelling event listeners, clearing timers, and aborting fetch requests on unmount without forcing consumer components to remember manual teardown.
## 2. Fundamental Custom Hook Patterns
### Pattern 1: Browser API & Event Abstraction (useEventListener)
Manually attaching and detaching event listeners inside UI components introduces boilerplate and frequently causes memory leaks when developers forget the cleanup return.
A dedicated hook wraps this setup cleanly while avoiding unnecessary listener re-attachments when the callback reference changes:
```ts
import { useEffect, useRef } from 'react';
export function useEventListener(
eventName: K,
handler: (event: WindowEventMap[K]) => void,
element: Window | HTMLElement | null = typeof window !== 'undefined' ? window : null
) {
// Store the latest handler in a ref to avoid re-binding the listener on every render
const savedHandler = useRef(handler);
useEffect(() => {
savedHandler.current = handler;
}, [handler]);
useEffect(() => {
if (!element?.addEventListener) return;
const listener = (event: Event) =>
savedHandler.current(event as WindowEventMap[K]);
element.addEventListener(eventName, listener);
return () => {
element.removeEventListener(eventName, listener);
};
}, [eventName, element]);
}
```
### Consumer Usage
```ts
export function Modal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
// One-line listener that safely cleans up on unmount or when dependencies change
useEventListener('keydown', (e) => {
if (e.key === 'Escape' && isOpen) {
onClose();
}
});
if (!isOpen) return null;
return (value: T) {
const ref = useRef(value);
// Synchronously update before screen paint
useLayoutEffect(() => {
ref.current = value;
});
return ref;
}
```
### Real-World Use Case: Stable Debounced Callback
```ts
import { useCallback, useEffect, useRef } from 'react';
import { useLatest } from './useLatest';
export function useDebouncedCallback any>(
callback: T,
delay: number
) {
const callbackRef = useLatest(callback);
const timeoutRef = useRef | null>(null);
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
}, []);
return useCallback(
(...args: Parameters) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
// Runs the freshest callback without needing it in the useCallback dependency array
callbackRef.current(...args);
}, delay);
},
[delay]
);
}
```
### Pattern 3: DOM Observation via Callback Ref (useIntersectionObserver)
Standard ref objects (useRef) do not notify React when a DOM element mounts or unmounts. If your component conditionally renders elements, ref.current might initially be null and attach later without triggering an effect re-run.
Using a Callback Ref guarantees that the observer attaches precisely when the physical DOM node mounts, and disconnects when it unmounts:
```ts
import { useState, useCallback, useRef } from 'react';
interface UseIntersectionObserverOptions extends IntersectionObserverInit {
freezeOnceVisible?: boolean;
}
export function useIntersectionObserver({
threshold = 0,
root = null,
rootMargin = '0%',
freezeOnceVisible = false,
}: UseIntersectionObserverOptions = {}) {
const [entry, setEntry] = useState(null);
const observerRef = useRef(null);
const isFrozen = entry?.isIntersecting && freezeOnceVisible;
// Callback ref: invoked whenever the attached DOM node changes
const ref = useCallback(
(node: HTMLElement | null) => {
if (observerRef.current) {
observerRef.current.disconnect();
observerRef.current = null;
}
if (isFrozen || !node) return;
observerRef.current = new IntersectionObserver(([entryUpdate]) => {
setEntry(entryUpdate);
}, { threshold, root, rootMargin });
observerRef.current.observe(node);
},
[threshold, root, rootMargin, isFrozen]
);
return { ref, entry, isIntersecting: !!entry?.isIntersecting };
}
```
### Consumer Usage
```ts
export function LazyLoadedCard() {
const { ref, isIntersecting } = useIntersectionObserver({
threshold: 0.2,
freezeOnceVisible: true,
});
return (
= {}) => ({
...userProps,
'aria-haspopup': 'menu' as const,
'aria-expanded': isOpen,
'aria-controls': menuId,
onClick: (e: React.MouseEvent) => {
userProps.onClick?.(e); // Keep the consumer's custom onClick working
if (!e.defaultPrevented) {
setIsOpen((prev) => !prev);
}
},
});
const getMenuProps = (userProps: React.HTMLAttributes = {}) => ({
...userProps,
id: menuId,
role: 'menu' as const,
hidden: !isOpen,
});
return {
isOpen,
setIsOpen,
getTriggerProps,
getMenuProps,
};
}
```
### Consumer Usage (Zero Manual Accessibility Plumbing)
```ts
export function NavigationMenu() {
const { isOpen, getTriggerProps, getMenuProps } = useDropdownMenu();
return (
Modal Content
;
}
```
### Pattern 2: The "Latest Ref" Pattern (useLatest)
One of the most common pitfalls in asynchronous React code is the stale closure—where an asynchronous operation, timer, or interval captures outdated state or props from an earlier render.
The useLatest pattern maintains a mutable ref that is updated synchronously before DOM mutations paint, allowing asynchronous closures to always inspect the freshest value without churning dependency arrays:
```ts
import { useRef, useLayoutEffect } from 'react';
export function useLatest
{isIntersecting ? : }
);
}
```
### Pattern 4: State Machine Toggle (useDisclosure)
Many components—drawers, dialogs, dropdowns, tooltips—share identical binary state mechanics. Abstracting this eliminates ad-hoc setIsModalOpen(true) calls across components:
```ts
import { useState, useCallback } from 'react';
export interface UseDisclosureReturn {
isOpen: boolean;
open: () => void;
close: () => void;
toggle: () => void;
setIsOpen: (isOpen: boolean) => void;
}
export function useDisclosure(initialState = false): UseDisclosureReturn {
const [isOpen, setIsOpen] = useState(initialState);
const open = useCallback(() => setIsOpen(true), []);
const close = useCallback(() => setIsOpen(false), []);
const toggle = useCallback(() => setIsOpen((prev) => !prev), []);
return { isOpen, open, close, toggle, setIsOpen };
}
```
## 3. Advanced Pattern: Prop Getters
When authoring complex headless hooks, merely returning raw states like isOpen forces the consumer to manually wire up accessibility attributes, focus management, and keyboard controls.
The Prop Getter pattern fixes this. The hook returns helper functions (such as getTriggerProps or getMenuProps) that bundle all necessary ARIA attributes, IDs, and event handlers into plain objects ready to be spread onto your JSX elements.
```ts
import { useState, useId } from 'react';
export function useDropdownMenu() {
const [isOpen, setIsOpen] = useState(false);
const menuId = useId();
const getTriggerProps = (userProps: React.ButtonHTMLAttributes
{/* Spread trigger props directly onto your custom button */}
{/* Spread menu props onto the container list */}
);
}
```
## 4. Best Practices & Common Traps
## 1. Avoid Returning Unstable Inline Functions
If your hook returns an object with fresh inline functions on every execution, any component or hook consuming those handlers will see referential changes on every render. This breaks React.memo optimizations and triggers unnecessary useEffect executions downstream.
```ts
// ❌ Problematic: Returns brand-new function references every render
export function useCounter() {
const [count, setCount] = useState(0);
return {
count,
increment: () => setCount((c) => c + 1) // Fresh reference every time
};
}
// ✅ Stable: Preserves referential equality
export function useCounter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount((c) => c + 1), []);
return { count, increment };
}
```
## 2. Don't Hide Side Effects in Component Bodies
Never execute raw side effects (such as updating external stores, setting local storage, or starting network fetches) directly in the body of a custom hook during the render phase. All side effects must live safely inside useEffect, useLayoutEffect, or event callbacks to keep rendering pure and compatible with Concurrent React.
## 3. Compose Small Primitives Instead of Monoliths
Avoid creating 600-line "god hooks" (like useDashboard) that handle network calls, form validation, modal state, and window resize listeners all in one giant function.
Instead, compose small, focused primitives together inside your feature hook:
```ts
export function useUserDashboard(userId: string) {
// Composed of discrete, single-purpose primitives
const { data: user, isLoading } = useQuery(['user', userId], () => fetchUser(userId));
const editModal = useDisclosure();
const deleteModal = useDisclosure();
const isOnline = useNetworkStatus();
return {
user,
isLoading,
editModal,
deleteModal,
isOnline,
};
}
```- Edit Profile
- Account Settings
- Log Out
