Sub topic 12
Building bigger hooks from smaller ones
This chapter assumes you can write a custom hook with useState and useEffect, and that you know the Rules of Hooks. It also assumes you have seen useDebouncedValue and useFetchJson from earlier chapters.
A hook is just a function that calls hooks
A custom hook can call other custom hooks. React doesn't treat them differently from built-in hooks. Every hook call in a component is recorded in order, and a hook that calls other hooks adds those calls to the same list.
Composition lets each hook do one job. You then combine them into a hook for a specific feature.
Example: a search hook
A search box has two jobs. It must wait until the user stops typing, and it must load results for the settled text. You already have a hook for each job.
import { useDebouncedValue } from './useDebouncedValue';
import { useFetchJson } from './useFetchJson';
export function useSearchResults(query, delay = 300) {
const debouncedQuery = useDebouncedValue(query, delay);
const url = `/api/search?q=${encodeURIComponent(debouncedQuery)}`;
const state = useFetchJson(url);
const isPending = query !== debouncedQuery;
return { ...state, isPending };
}The new hook has no effects of its own. It wires the output of one hook into the input of the next. When query changes, useDebouncedValue waits, then returns a new value. That changes url, which makes useFetchJson start a new request and discard the old one.
A component then reads like a description of what it shows:
import { useState } from 'react';
import { useSearchResults } from './useSearchResults';
function SearchBox() {
const [query, setQuery] = useState('');
const { status, data, error, isPending } = useSearchResults(query);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
{(isPending || status === 'loading') && <p>Searching...</p>}
{status === 'error' && <p>Failed: {error.message}</p>}
{status === 'success' && <pre>{JSON.stringify(data, null, 2)}</pre>}
</>
);
}Rules that keep composition safe
- Pass values down, not hidden state. The inner hook gets what it needs as arguments. Two hooks should not read the same module-level variable to coordinate.
- Keep call order fixed. Never call an inner hook inside an
ifor a loop. If you need conditional behavior, pass a flag or anullinput and handle it inside the inner hook. - Return a small, clear shape. Spread or pick only what callers need. Here
isPendingis new information that neither inner hook could compute alone. - Let each layer own its cleanup. The outer hook should not repeat the timer or abort logic. The inner hooks already do that.
When to stop composing
A composed hook is worth it when it names a real feature, such as search or pagination. Avoid layers that only rename another hook, because they hide where behavior comes from. If you cannot say in one sentence what the hook does, split it or inline it.
A practical check: can you test each inner hook alone and the outer hook with only its wiring in mind? If yes, the layers are sound.
Exercise
useSearchResults fetches /api/search?q= when the query is an empty string. Which change keeps the composition but avoids that request, and where should it be made?
Show answer
Make useFetchJson accept null as the url and skip the request in that case, then pass null from useSearchResults when debouncedQuery is empty. The hook call itself stays unconditional, so the order of hooks does not change. The skip logic belongs inside the inner hook, because an if around the call would break the Rules of Hooks.