Sub topic 12
Building bigger hooks from smaller ones
This chapter assumes you know function components, JSX, useState and useEffect, and that you have written at least one custom hook. You should also know that each call to a hook creates its own state. Here you will build larger hooks by calling smaller hooks inside them, and you will see where that approach works well and where it goes wrong.
Why composition works
A custom hook is a function that calls other hooks. Nothing in React limits how deep this goes. A hook can call useState, another custom hook, or five of them. React tracks every hook call by its position in the render order, so a composed hook follows the same Rules of Hooks as a component. Call hooks at the top level, never inside conditions, loops or nested functions.
Composition gives you three things:
- Small pieces you can name.
useDebouncedValueanduseFetchJsoneach do one job and are easy to read. - Reuse at several levels. The same small hook can appear in many larger hooks.
- Isolated state. Every call has its own state, so combining hooks never makes them interfere with each other.
State stays inside each call
When a larger hook calls a smaller one, the smaller hook's state belongs to the larger hook's caller. Two components that use the larger hook get two separate copies of everything inside it.
A worked example: search as you type
A search box needs three things. It must keep the user's text in state, wait until typing pauses, and load results for the paused text. The two hooks below are the small pieces. They are the same hooks you would write on their own.
import { useState, useEffect } from 'react';
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}import { useState, useEffect } from 'react';
export function useFetchJson(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => {
if (!ignore) setState({ status: 'success', data, error: null });
})
.catch((error) => {
if (!ignore && error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}Now the composed hook. It owns the query text, passes it through the debouncer, builds a URL, and hands the URL to the fetcher.
import { useState } from 'react';
import { useDebouncedValue } from './useDebouncedValue';
import { useFetchJson } from './useFetchJson';
export function useSearch(baseUrl, delay = 300) {
const [query, setQuery] = useState('');
const debouncedQuery = useDebouncedValue(query, delay);
const url = `${baseUrl}?q=${encodeURIComponent(debouncedQuery)}`;
const result = useFetchJson(url);
return { query, setQuery, ...result };
}A component then needs very little code:
import { useSearch } from './useSearch';
function SearchBox() {
const { query, setQuery, status, data, error } = useSearch('/api/items');
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
{status === 'loading' && <p>Loading...</p>}
{status === 'error' && <p>Error: {error.message}</p>}
{status === 'success' && (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</>
);
}Follow one keystroke through the system:
- The user types.
setQueryupdatesqueryand the component re-renders. useDebouncedValuesees a newvalue. Its effect cleanup clears the old timer and starts a new one.- After
delaymilliseconds with no further typing, the timer setsdebounced.debouncedQuerychanges on the next render. - The
urlstring changes, so the effect inuseFetchJsoncleans up the previous request and starts a new one.
The composed hook has no effects of its own. Its dependencies are handled inside the hooks it calls. That is the main benefit: each smaller hook already has correct dependencies and cleanup, and the larger hook inherits both.
Passing data between hooks
Hooks communicate through values, not through hidden channels. The output of one hook becomes the input of the next, as debouncedQuery does above. This has two consequences.
First, the data flow is visible. You can read useSearch from top to bottom and see where each value comes from.
Second, every value you pass into an effect-based hook becomes part of that hook's dependency array. Pass primitives when you can. A string like url compares by value, so the effect re-runs only when the text changes. An object or array you build during render is a new reference every time, so the effect re-runs on every render.
import { useEffect } from 'react';
// Re-runs on every render, because `options` is a new object each time.
export function useBadExample(url) {
const options = { headers: { Accept: 'application/json' } };
useEffect(() => {
fetch(url, options);
}, [url, options]);
}Fix this by moving constant values outside the hook, by passing primitives, or by memoizing the object with useMemo.
Designing the combined return value
A composed hook must decide what to expose. Three common choices:
| Choice | Example | Use it when |
|---|---|---|
| Return everything | `{ query, setQuery, ...result }` | The caller needs most of the inner values. |
| Return a narrowed result | `{ items, isLoading }` | You want to hide inner details and keep freedom to change them. |
| Return a tuple | `[value, toggle]` | There are two or three values and callers will rename them. |
Spreading an inner hook's result, as useSearch does, is convenient. It also makes the inner hook's shape part of your public API. If useFetchJson later adds a field, every caller of useSearch sees it. If you rename a field, you break them. When a hook is used across a large codebase, return a deliberately chosen object.
Layering without hiding too much
Composition invites deep stacks, where a hook calls a hook that calls a hook. Some guidelines keep them manageable:
- Give each layer one reason to exist.
useDebouncedValuehandles timing.useFetchJsonhandles loading.useSearchjoins them with search-specific rules. - Keep generic hooks free of domain knowledge.
useFetchJsonknows nothing about search, so other features can use it. - Put domain rules in the top layer. The
?q=URL format belongs inuseSearch, not in a generic hook. - Let callers reach the lower layers. A component that needs only debouncing should be able to import
useDebouncedValuedirectly.
Composing with refs and stable callbacks
Larger hooks often combine state with event listeners. The useEventListener hook from earlier chapters keeps the latest handler in a ref, so callers do not need to memoize their handlers. You can build on it:
import { useState, useEffect, useRef } from 'react';
function useEventListener(type, handler, target = window) {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
});
useEffect(() => {
const listener = (event) => handlerRef.current(event);
target.addEventListener(type, listener);
return () => target.removeEventListener(type, listener);
}, [type, target]);
}
export function useKeyPressed(key) {
const [pressed, setPressed] = useState(false);
useEventListener('keydown', (e) => {
if (e.key === key) setPressed(true);
});
useEventListener('keyup', (e) => {
if (e.key === key) setPressed(false);
});
return pressed;
}useKeyPressed passes a new arrow function on every render. That is safe, because useEventListener stores the handler in a ref and attaches the real listener only once per type and target. The lower layer absorbs the instability, so the higher layer stays simple. A hook that did not use a ref would force useKeyPressed to wrap its handlers in useCallback.
Pitfalls specific to composition
Conditional hook calls
You cannot skip a smaller hook based on a prop:
// Invalid: the hook call is conditional.
function useMaybeFetch(url, enabled) {
if (enabled) {
return useFetchJson(url);
}
return null;
}Instead, make the hook accept the condition and decide inside. For example, useFetchJson could take null as the url and skip the request. The call always happens, and the effect chooses what to do.
Duplicated state across layers
If a larger hook keeps its own copy of a value that a smaller hook also keeps, the two can drift apart. Keep one source of truth and pass it down, as useSearch does with query.
Cascading renders
Each layer that stores state in an effect can add a render. useDebouncedValue renders once when the timer fires. Chains of such hooks, where each one waits for the previous result in an effect, produce several renders in a row. If a value can be computed from other values during render, compute it there instead of storing it in state.
Wrappers that add nothing
A hook that only calls one other hook and returns its result, with no new rule or name worth having, is noise. Delete the wrapper.
Summary of the approach
- Start with small hooks that each do one thing.
- Pass values from one hook into the next.
- Keep one source of truth for each piece of state.
- Return a deliberately shaped result from the top layer.
- Never make a hook call conditional.
Exercise
A teammate writes useSearch so that it keeps its own debouncedQuery in useState and updates it with an effect, instead of calling useDebouncedValue. Name two problems with that design, and say what you would do instead.
Show answer
First, it duplicates timer logic that useDebouncedValue already implements and tests, so a bug fix has to be made in several places. Second, it mixes timing concerns with search rules, so the timing code cannot be reused by other features. Replace the inline state and effect with a call to useDebouncedValue(query, delay), and pass its result into useFetchJson.
Exercise
You want useFetchJson to skip the request when a search box is empty. Why is if (query) { return useFetchJson(url); } invalid, and how would you change useFetchJson so the call can stay unconditional?
Show answer
A conditional call changes the order of hook calls between renders, which breaks the Rules of Hooks. Change useFetchJson to accept null for the url. Inside its effect, return early when url is null and set an idle state. The component always calls the hook, and the effect decides whether to fetch.