ReactEasy
Custom Hooks Pattern?
The custom hooks pattern moves reusable stateful logic into functions named useSomething that compose built-in hooks, so components stay focused on rendering. It replaced higher-order components and render props as the main way to share logic, and it is how libraries such as TanStack Query, React Hook Form and Zustand expose their APIs.
Typical custom hooks
- Data:
useUser(id),useProducts(filters)wrapping TanStack Query. - Browser APIs:
useMediaQuery,useOnlineStatus,useLocalStorage,useIntersectionObserver. - Timing:
useDebounce,useInterval,useThrottle. - UI behavior:
useDisclosure(open/close),useClickOutside,useFocusTrap. - Domain logic:
useCart,useCheckout,usePermissions.
Design guidelines
- Single purpose and a descriptive name.
- Accept parameters, return a clear API: a value, a tuple for state-like hooks, or an object for many values.
- Stable return values (memoized functions) when consumers may use them in dependencies, or rely on the React Compiler.
- Clean up subscriptions and timers.
- Avoid effects for things that can be derived; a hook can compute values during render.
- Build on
useSyncExternalStorefor external sources. - Do not hide too much: a hook that fetches, writes to a store and navigates is hard to reuse.
Testing
renderHook(() => useDebounce(value, 300)) with fake timers, or test through a component that uses it.
Sharing state
Custom hooks share logic, not state. Wrap a context or store for shared state.
Code example
tsx
1import { useEffect, useState } from "react";23export function useDebounce<T>(value: T, delay = 300) {4 const [debounced, setDebounced] = useState(value);5 useEffect(() => {6 const id = setTimeout(() => setDebounced(value), delay);7 return () => clearTimeout(id);8 }, [value, delay]);9 return debounced;10}1112export function useDisclosure(initial = false) {13 const [isOpen, setIsOpen] = useState(initial);14 return {15 isOpen,16 open: () => setIsOpen(true),17 close: () => setIsOpen(false),18 toggle: () => setIsOpen((o) => !o),19 };20}2122// Composed in a component: logic is reusable, rendering stays simple23export function SearchPanel() {24 const panel = useDisclosure();25 const [query, setQuery] = useState("");26 const debouncedQuery = useDebounce(query, 400);2728 useEffect(() => {29 if (debouncedQuery) console.log("search", debouncedQuery);30 }, [debouncedQuery]);3132 return (33 <div>34 <button onClick={panel.toggle}>{panel.isOpen ? "Close" : "Search"}</button>35 {panel.isOpen && <input autoFocus value={query} onChange={(e) => setQuery(e.target.value)} />}36 </div>37 );38}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.