What You'll Learn
- 1Spot the duplication that signals a custom hook is warranted
- 2Design a hook API that stays stable as features are added
- 3Compose small hooks instead of building one configurable hook
- 4Test a hook's behaviour without rendering a whole page
The smell that signals a custom hook
Duplication in React is rarely about markup. It is about the dance of state, effects, and handlers that two components perform in parallel: a form that tracks whether a request is in flight, a list that paginates itself, a media element that exposes play and pause. When the second component starts copying the first, the logic has become a candidate for extraction, and the extraction is a function that calls hooks.
The signal is stronger when the dance includes cleanup. Two components that both subscribe to something and both forget to unsubscribe will produce the same production incident twice. Moving the subscription into a shared hook fixes it once, documents the lifetime in one place, and gives you a single surface to test. The alternative, a higher-order component or a wrapper component, costs you an extra node in the tree and obscures the prop flow, which is exactly what hooks were introduced to avoid.
Anatomy of a hook
A custom hook is an ordinary function whose name starts with use. It can call state, effect, context, and other hooks, and it can return anything: a value, an array, an object, or a set of callbacks. The name is not decoration; the lint rules that enforce the hook contract look for that prefix, and developers reading your code expect it to obey the rules.
function useOnlineStatus(url) {
const [online, setOnline] = useState(true);
const [checkedAt, setCheckedAt] = useState(null);
useEffect(() => {
let cancelled = false;
const ping = async () => {
try {
const res = await fetch(url, { method: 'HEAD' });
if (!cancelled) setOnline(res.ok);
} catch {
if (!cancelled) setOnline(false);
} finally {
if (!cancelled) setCheckedAt(new Date());
}
};
ping();
const interval = setInterval(ping, 15000);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [url]);
return { online, checkedAt, refresh: () => setCheckedAt(new Date()) };
}
Three properties make this a good hook. It owns its own cleanup, so no caller can leak the interval. It returns a small, named surface rather than its internal state, so the implementation can change without breaking callers. And it takes its configuration as arguments rather than reading a global, which keeps it testable.
Persisting state without lying to the user
One of the most copied snippets on the web is a local storage hook, and the naive version has two bugs: it reads storage during the first render, which breaks server rendering and any environment without storage, and it writes on every keystroke, which is fine until it is not.
function useStoredState(key, initialValue) {
const [value, setValue] = useState(initialValue);
useEffect(() => {
try {
const raw = window.localStorage.getItem(key);
if (raw !== null) setValue(JSON.parse(raw));
} catch {
window.localStorage.removeItem(key);
}
}, [key]);
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch {
// storage may be full or blocked; state still works in memory
}
}, [key, value]);
return [value, setValue];
}
Reading inside an effect means the first render is consistent on the server and the client, and hydration mismatches disappear. The write effect acknowledges that storage can fail and treats persistence as best effort rather than as a precondition for the component to work. Both choices come from writing the hook once, carefully, instead of copying it into six files.
Composition over configuration
A hook that takes eight options is really three hooks in a trench coat. Composing small hooks keeps each one testable and lets callers assemble exactly the behaviour they need, while configuration objects grow until the documentation is longer than the implementation.
| Approach | Shape | Trade-off |
|---|---|---|
| One hook with an options object | usePaginator({ total, pageSize, window }) | Flexible, but every new option touches every caller |
| Several single-purpose hooks | usePage(), usePageSize(), useWindow() | Callers wire them together, which is explicit and clear |
| A hook built from other hooks | usePaginatedQuery composing the two above | Best of both, if the composition is genuinely stable |
| A hook returning a reducer | usePaginatorReducer() | Scales to complex state machines, at the cost of indirection |
The rule of thumb is to compose until the composition itself feels wrong. When two hooks are always used together, wrap them in a third that returns the combined surface. When they are used separately as often as together, leave the wiring to the caller.
Hooks that wrap context, and the rules that still apply
A common request is a hook that reads context for the caller, hiding the useContext call behind a friendly name. This is a good pattern when the hook owns the whole capability, such as useSession or useTheme, and it is a poor pattern when the hook is doing more than one thing. A hook that fetches data and also reads a token from context is two responsibilities joined at the hip, and testing either half requires mocking the other.
Conditional logic is the other trap. Because hooks must be called in the same order on every render, a custom hook cannot decide to skip useState based on an argument. Branch on the argument inside the hook instead, or return early from the caller's render rather than from the hook body. The same rule blocks loops: you cannot build a dynamic number of hooks by mapping over a config array, and the workaround is to build a child component per item so each one owns its own hooks.
Both constraints look like limitations until you see what they protect. Consistent hook order is what allows the state slots to line up between renders, and consistent hook count is what keeps the component's contract with React stable. Writing hooks that respect both is what makes them safe to extract, test, and reuse across a codebase.
Naming, structure, and API shape
Naming decides whether a hook reads well at the call site, and the call site is where the API is judged. A hook that returns a boolean should read as a question: useIsOnline, useHasScrolled. A hook that returns a tuple should follow the useState convention of value and setter, so the destructuring looks familiar. A hook that returns several unrelated things should return an object, because positional destructuring of a four-item array is where bugs hide.
Place hooks next to the components that use them until a second feature needs them, then promote them to a shared hooks directory with a test file alongside. Export the hook and its types together, and avoid reaching for internal state variables in the return value; a hook that leaks its own useState tuple forces callers to depend on your implementation.
Testing hooks without a page
A hook is a function, which means it can be exercised by rendering a tiny probe component and asserting on what it returns. The probe exists only to give the hook a place to live, since hooks require a React render context.
function useCounter(start = 0) {
const [count, setCount] = useState(start);
const increment = () => setCount((c) => c + 1);
return { count, increment };
}
function renderProbe(useHook) {
const result = { current: undefined };
function Probe() {
result.current = useHook();
return null;
}
render(<Probe />);
return result;
}
test('increments a counter hook', () => {
const result = renderProbe(() => useCounter(5));
act(() => result.current.increment());
expect(result.current.count).toBe(6);
});
For hooks with timers or requests, fake timers and a stub fetch keep the test deterministic. Assert on behaviour rather than on internal state, and include the cleanup path: mount, change the inputs, unmount, and verify that nothing throws and that the interval or listener was released.
Common Mistakes
Extracting a hook before the second use case appears, guessing at options nobody needs
Fix: Wait for real duplication, then extract the logic you actually have
Returning internal state directly so the implementation cannot change
Fix: Return a named surface that describes intent rather than storage
Reading storage or the network during the first render inside the hook
Fix: Do it in an effect so server and client agree on the initial output
Building one configurable hook instead of two small composable ones
Fix: Split by responsibility and compose the pieces that are always used together
Best Practices
- Prefix every hook with use and keep the lint rules that enforce the contract enabled
- Own all cleanup inside the hook so callers cannot leak resources
- Return objects with named fields unless you are deliberately matching the useState convention
- Write the test file at the same time as the hook, while the edge cases are still in your head
- Promote a hook to a shared location only after a second feature depends on it
Key Takeaways
- Custom hooks extract stateful logic, and the use prefix is what makes the rules apply to them
- A good hook owns its cleanup and returns a small, intent-revealing surface
- Read external systems in effects, and treat persistence as best effort
- Compose small hooks rather than growing one options object forever
- Test hooks through a probe component, and cover the unmount path as well as the happy path