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

  1. Single purpose and a descriptive name.
  2. Accept parameters, return a clear API: a value, a tuple for state-like hooks, or an object for many values.
  3. Stable return values (memoized functions) when consumers may use them in dependencies, or rely on the React Compiler.
  4. Clean up subscriptions and timers.
  5. Avoid effects for things that can be derived; a hook can compute values during render.
  6. Build on useSyncExternalStore for external sources.
  7. 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";
2
3export 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}
11
12export 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}
21
22// Composed in a component: logic is reusable, rendering stays simple
23export function SearchPanel() {
24 const panel = useDisclosure();
25 const [query, setQuery] = useState("");
26 const debouncedQuery = useDebounce(query, 400);
27
28 useEffect(() => {
29 if (debouncedQuery) console.log("search", debouncedQuery);
30 }, [debouncedQuery]);
31
32 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.

Open in study app