Custom Hook Composition in React
How to compose reusable logic with custom React hooks. Covers hook composition, dependency arrays, context integration, memoization, and testing.
Overview
Custom hook composition is the practice of building complex logic by combining smaller, focused hooks. Instead of one large hook that does everything, you compose several single-purpose hooks (useFetch, useDebounce, useSort, usePagination) into a higher-level hook like useUserTable. Each hook owns one concern, so you can test it in isolation and drop it into other components without rewiring.
This is the React version of function composition: small functions that do one thing, wired together to solve a bigger problem. The payoff shows up when a second screen needs the same table behavior but a different data source — you swap useFetch for useProtectedFetch and keep everything else.
When to Use
- Two or more components share the same data-fetching and transformation logic
- Component logic grows past 50–100 lines and handles more than one concern
- You need to test business logic independently of rendering
- Different screens need different combinations of the same building blocks
- State management logic is duplicated across components
When NOT to Use
- Simple components with straightforward logic — a single
useStateis enough - Hooks used in exactly one place that are simple enough to inline
- Cases where the composition adds indirection without improving clarity
- Logic that never touches React state or effects — that’s a plain utility function, not a hook
Solution
Basic custom hooks
// useDebounce.js — debounce a value
import { useState, useEffect } from 'react';
function useDebounce(value, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;
// useFetch.js — data fetching with loading/error states
import { useState, useEffect, useCallback, useRef } from 'react';
function useFetch(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(!!url);
const [error, setError] = useState(null);
const optionsRef = useRef(options);
const fetchData = useCallback(async () => {
if (!url) {
setData(null);
setLoading(false);
return;
}
setLoading(true);
setError(null);
try {
const response = await fetch(url, optionsRef.current);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const json = await response.json();
setData(json);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}, [url]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch: fetchData };
}
export default useFetch;
// useSort.js — sort an array by key
import { useState, useMemo } from 'react';
function useSort(items, initialKey = null, initialDirection = 'asc') {
const [sortKey, setSortKey] = useState(initialKey);
const [sortDirection, setSortDirection] = useState(initialDirection);
const sortedItems = useMemo(() => {
if (!sortKey) return items;
const sorted = [...items].sort((a, b) => {
if (a[sortKey] < b[sortKey]) return sortDirection === 'asc' ? -1 : 1;
if (a[sortKey] > b[sortKey]) return sortDirection === 'asc' ? 1 : -1;
return 0;
});
return sorted;
}, [items, sortKey, sortDirection]);
const toggleSort = (key) => {
if (sortKey === key) {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
} else {
setSortKey(key);
setSortDirection('asc');
}
};
return { sortedItems, sortKey, sortDirection, toggleSort };
}
export default useSort;
// usePagination.js — paginate an array
import { useState, useMemo } from 'react';
function usePagination(items, itemsPerPage = 10) {
const [currentPage, setCurrentPage] = useState(1);
const totalPages = Math.ceil(items.length / itemsPerPage);
const paginatedItems = useMemo(() => {
const start = (currentPage - 1) * itemsPerPage;
return items.slice(start, start + itemsPerPage);
}, [items, currentPage, itemsPerPage]);
const nextPage = () => setCurrentPage(prev => Math.min(prev + 1, totalPages));
const prevPage = () => setCurrentPage(prev => Math.max(prev - 1, 1));
const goToPage = (page) => setCurrentPage(Math.min(Math.max(page, 1), totalPages));
return {
paginatedItems,
currentPage,
totalPages,
nextPage,
prevPage,
goToPage,
};
}
export default usePagination;
Composing hooks into a higher-level hook
// useUserTable.js — composed hook combining fetch, debounce, sort, pagination
import useFetch from './useFetch';
import useDebounce from './useDebounce';
import useSort from './useSort';
import usePagination from './usePagination';
import { useMemo } from 'react';
function useUserTable(searchQuery, options = {}) {
const debouncedQuery = useDebounce(searchQuery, options.debounceDelay || 300);
const url = useMemo(() => {
const params = new URLSearchParams();
if (debouncedQuery) params.set('q', debouncedQuery);
return `/api/users?${params.toString()}`;
}, [debouncedQuery]);
const { data: users, loading, error, refetch } = useFetch(url);
const { sortedItems, sortKey, sortDirection, toggleSort } = useSort(
users || [],
options.initialSortKey,
options.initialSortDirection || 'asc',
);
const {
paginatedItems,
currentPage,
totalPages,
nextPage,
prevPage,
goToPage,
} = usePagination(sortedItems, options.itemsPerPage || 10);
return {
users: paginatedItems,
loading,
error,
sortKey,
sortDirection,
toggleSort,
currentPage,
totalPages,
nextPage,
prevPage,
goToPage,
refetch,
};
}
export default useUserTable;
// UserTable.jsx — component using the composed hook
import React, { useState } from 'react';
import useUserTable from '../hooks/useUserTable';
function UserTable() {
const [searchQuery, setSearchQuery] = useState('');
const {
users,
loading,
error,
sortKey,
sortDirection,
toggleSort,
currentPage,
totalPages,
nextPage,
prevPage,
goToPage,
} = useUserTable(searchQuery, {
itemsPerPage: 5,
initialSortKey: 'name',
debounceDelay: 200,
});
return (
<div className="user-table">
<input
type="search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search users..."
/>
{loading && <div>Loading...</div>}
{error && <div className="error">{error}</div>}
<table>
<thead>
<tr>
<th onClick={() => toggleSort('name')}>
Name {sortKey === 'name' && (sortDirection === 'asc' ? '↑' : '↓')}
</th>
<th onClick={() => toggleSort('email')}>
Email {sortKey === 'email' && (sortDirection === 'asc' ? '↑' : '↓')}
</th>
</tr>
</thead>
<tbody>
{users.map(user => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
</tr>
))}
</tbody>
</table>
<div className="pagination">
<button onClick={prevPage} disabled={currentPage === 1}>Previous</button>
<span>Page {currentPage} of {totalPages}</span>
<button onClick={nextPage} disabled={currentPage === totalPages}>Next</button>
</div>
</div>
);
}
export default UserTable;
Context-integrated composition
Context is another composition point: a hook backed by a provider (like useAuth) can feed tokens into other hooks. For when context is the right tool versus an external store, see the React State Management guide:
// useAuth.js — auth hook backed by context
import { useContext } from 'react';
import AuthContext from '../context/AuthContext';
function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
const { user, token, login, logout, isLoading } = context;
return { user, token, login, logout, isLoading, isAuthenticated: !!user };
}
export default useAuth;
// useProtectedFetch.js — compose useAuth with a fetch hook
import useAuth from './useAuth';
import { useState, useEffect, useCallback } from 'react';
function useProtectedFetch(url) {
const { token, logout } = useAuth();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchData = useCallback(async () => {
if (!token) {
setError('Not authenticated');
setLoading(false);
return;
}
setLoading(true);
try {
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
});
if (response.status === 401) {
logout();
throw new Error('Session expired');
}
const json = await response.json();
setData(json);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}, [url, token, logout]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch: fetchData };
}
export default useProtectedFetch;
Memoization in composed hooks
// useFilteredAndSortedData.js — memoized composition
import { useMemo } from 'react';
import useSort from './useSort';
function useFilteredAndSortedData(items, filters, sortKey) {
const filteredItems = useMemo(() => {
return items.filter(item => {
return Object.entries(filters).every(([key, value]) => {
if (!value) return true;
return String(item[key]).toLowerCase().includes(String(value).toLowerCase());
});
});
}, [items, filters]);
const { sortedItems, sortKey: activeKey, sortDirection, toggleSort } = useSort(
filteredItems,
sortKey,
);
return { items: sortedItems, sortKey: activeKey, sortDirection, toggleSort };
}
export default useFilteredAndSortedData;
Testing custom hooks
// useDebounce.test.js
import { renderHook, act } from '@testing-library/react';
import useDebounce from './useDebounce';
describe('useDebounce', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('returns initial value immediately', () => {
const { result } = renderHook(() => useDebounce('initial', 300));
expect(result.current).toBe('initial');
});
it('updates value after delay', () => {
const { result, rerender } = renderHook(({ value }) => useDebounce(value, 300), {
initialProps: { value: 'initial' },
});
rerender({ value: 'updated' });
expect(result.current).toBe('initial');
act(() => {
jest.advanceTimersByTime(300);
});
expect(result.current).toBe('updated');
});
it('cancels previous timer on rapid changes', () => {
const { result, rerender } = renderHook(({ value }) => useDebounce(value, 300), {
initialProps: { value: 'a' },
});
rerender({ value: 'b' });
act(() => jest.advanceTimersByTime(200));
rerender({ value: 'c' });
act(() => jest.advanceTimersByTime(200));
expect(result.current).toBe('a');
act(() => jest.advanceTimersByTime(100));
expect(result.current).toBe('c');
});
});
// useFetch.test.js
import { renderHook, waitFor } from '@testing-library/react';
import useFetch from './useFetch';
describe('useFetch', () => {
it('fetches data on mount', async () => {
const mockData = [{ id: 1, name: 'Alice' }];
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(mockData),
});
const { result } = renderHook(() => useFetch('/api/users'));
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.data).toEqual(mockData);
expect(result.current.error).toBeNull();
});
it('handles fetch errors', async () => {
global.fetch = jest.fn().mockRejectedValue(new Error('Network error'));
const { result } = renderHook(() => useFetch('/api/users'));
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.data).toBeNull();
expect(result.current.error).toBe('Network error');
});
});
Explanation
Why composition beats one big hook
A single useUserTable written from scratch would mix four concerns: input debouncing, HTTP state, sorting, and paging. Each of those has its own edge cases and its own tests. Once they’re separate hooks, you test useDebounce with fake timers and never think about it again; the table hook reads like a wiring diagram instead of a wall of logic.
There’s a practical ordering rule too. Composition works top-down: each hook consumes the output of the previous one. In useUserTable, the debounced query builds the URL, the URL feeds useFetch, the fetched items feed useSort, and the sorted items feed usePagination. If you reorder that chain, the data no longer flows correctly.
The rules of hooks still apply inside composed hooks
A custom hook is just a function that calls other hooks, so every rule applies: call hooks unconditionally at the top level, never inside loops, conditions, or nested functions. You can’t skip a composed hook mid-chain because a feature is “disabled” — instead you keep the call and gate the behavior inside it. That’s exactly what the enabled flag does in the conditional variant below: useFetch still runs, but a null URL makes it a no-op.
Two failure modes deserve special attention:
- Stale closures. A
useCallbackoruseMemoinside a composed hook captures the values in its dependency array. Forget one and the hook silently works with old data — the classic symptom is “sort works but ignores new filters”.useFetchabove readsoptionsthrough a ref for the same reason: callers pass a fresh object every render, and depending on it directly would refetch on every render. - Context guards. If a hook depends on context, check the value returned by
useContext, not the context object itself.useContext(AuthContext)returnsundefinedoutside the provider — that’s what theuseAuthguard checks. Testingif (!AuthContext)looks right but is dead code, and destructuring first throws a confusing TypeError instead of your clear message.
Where memoization fits
Composed hooks return new object identities every render. That’s fine until you pass a callback to a memoized child or list a returned value in another useEffect dependency array — then identity changes trigger extra renders and effects. Memoize the expensive derivation (useMemo for filtered/sorted data), stabilize callbacks (useCallback for toggleSort if it reaches memoized children), and document which return values are stable. For when memoization actually pays off — and when it’s wasted work — see useMemo and useCallback for Performance.
Trade-off to keep in mind
Every layer of composition is a layer of indirection for the next reader. If a hook is used once and its logic fits on a screen, extracting it costs more clarity than it buys. A useful heuristic: extract when logic is reused, when it needs isolated tests, or when it describes a named concept (useDebounce) rather than a step in one component.
Design the return value as an API, then test the seams
The object a composed hook returns is a public contract, not an implementation detail: renaming sortedItems to items breaks every consumer. Pick stable key names, keep them flat while they’re few, and don’t return more than callers need — a long destructure in UserTable is a sign the hook does too much. If the object grows, group related fields (pagination: { page, total, next, prev } reads better than six sibling keys), but treat grouping as a breaking change and do it before the hook has consumers.
Testing follows the composition boundary. Each leaf hook gets its own renderHook suite — fake timers for useDebounce, a mocked fetch for useFetch — and the composed hook gets a thin wiring test: push a query through, assert which URL useFetch received and the shape of the returned object. Resist retesting leaf behavior at the composition level; if useDebounce is covered, useUserTable only needs to prove the wiring exists. For context-backed hooks like useProtectedFetch, wrap renderHook in the provider and let the real guard fire — that’s the one branch worth exercising at every level.
Variants
Hook with reducer for complex state
// useAsyncReducer.js — manage async operations with reducer
import { useReducer, useCallback } from 'react';
const initialState = { loading: false, data: null, error: null };
function asyncReducer(state, action) {
switch (action.type) {
case 'start':
return { loading: true, data: null, error: null };
case 'success':
return { loading: false, data: action.data, error: null };
case 'error':
return { loading: false, data: null, error: action.error };
default:
return state;
}
}
function useAsyncReducer(asyncFn) {
const [state, dispatch] = useReducer(asyncReducer, initialState);
const execute = useCallback(async (...args) => {
dispatch({ type: 'start' });
try {
const data = await asyncFn(...args);
dispatch({ type: 'success', data });
return data;
} catch (err) {
dispatch({ type: 'error', error: err.message });
throw err;
}
}, [asyncFn]);
return { ...state, execute };
}
export default useAsyncReducer;
Conditional hook composition
// useUserData.js — conditional behavior via an enabled flag
function useUserData(userId, options = {}) {
const { enabled = true } = options;
// Hooks always run — the null URL makes useFetch a no-op when disabled
const { data, loading, error, refetch } = useFetch(
enabled ? `/api/users/${userId}` : null,
);
// Results are still processed conditionally
const user = useMemo(() => {
if (!enabled || !data) return null;
return {
...data,
displayName: `${data.firstName} ${data.lastName}`,
initials: `${data.firstName[0]}${data.lastName[0]}`,
};
}, [data, enabled]);
return { user, loading: enabled && loading, error: enabled ? error : null, refetch };
}
Best Practices
- One concern per hook:
useDebounceonly debounces,useSortonly sorts. Don’t mix concerns. - Compose, don’t duplicate — if two hooks share logic, extract a third hook and compose it into both.
- Return objects, not arrays —
{ data, loading, error }is self-documenting and order-independent. - Memoize expensive computations —
useMemofor derived data,useCallbackfor functions passed to memoized children. - Keep dependency arrays honest — stale closures are the most common hook bug; include every referenced value or read through a ref.
- Name hooks with the
useprefix — it’s what lets the linter enforce the rules of hooks. - Guard the context value, not the context object —
const ctx = useContext(Ctx); if (!ctx) throw. - Test hooks with
renderHookfrom@testing-library/react— the old@testing-library/react-hookspackage is deprecated.
For the component-side counterpart, see Container-Presenter: Separate Data Logic from Rendering.
Common Mistakes
- Violating the rules of hooks: calling hooks conditionally or in loops. Gate behavior inside the hook, not the call.
- Passing
nullinto a hook that doesn’t handle it:fetch(null)requests the URL"null". If a hook can receive a disabled input, make it a no-op explicitly. - Stale closures: forgetting a dependency in the dependency array. The callback captures old values.
- Over-composing: wrapping a single
useStatein a hook. Only extract when logic is non-trivial or reused. - Returning too much: a hook that returns 15 values is hard to use. Split it or group related values.
- Not memoizing callbacks: passing new function references to memoized children causes extra re-renders.
See Also
- Container-Presenter: Separate Data Logic from Rendering
- React docs — Reusing Logic with Custom Hooks
- React docs — Rules of Hooks
- Testing Library — React Hooks testing
- Companion resources — the seven hooks plus a
renderHooktest suite, ready to copy into a project
Frequently Asked Questions
What is hook composition?
Combining several custom hooks into a higher-level hook. For example, useUserTable composes useFetch, useDebounce, useSort, and usePagination into one hook that manages a data table.
Can I call hooks conditionally?
No. The rules of hooks require hook calls to run unconditionally at the top level. The idiomatic pattern is an enabled option: the hook still runs every render, but skips its work when the flag is off.
Should hooks return objects or arrays?
Objects are usually better — self-documenting and order-independent. Arrays work fine for hooks returning two or three positional values, like useState.
How do I test custom hooks?
Use renderHook from @testing-library/react. It mounts the hook in a minimal harness so you can test it without writing a component. Pair it with jest.useFakeTimers() for time-based hooks.
When should I extract logic into a custom hook?
When the logic is reused in more than one component, when it needs tests independent of rendering, or when naming it (useDebounce) makes the calling code clearer than the inline version.
What's the difference between a custom hook and a utility function?
A custom hook calls React hooks (useState, useEffect, and so on) and participates in the component lifecycle. A utility function is pure and stateless. If it needs React state or effects, it's a hook; otherwise keep it a plain function.
Related Resources
Container-Presenter: Separate Data Logic from Rendering
How to separate data-fetching logic from rendering in React using the container-presenter pattern. Covers hooks migration, testing benefits, and trade-offs.
PatternOptimistic Update Pattern
How to update UI instantly and reconcile with the server in React: rollback on error, temp IDs, conflict handling, React 19 useOptimistic, and React Query.
PatternState Machine UI: Finite State Machines for UI
How to model UI state transitions with finite state machines in React. Covers XState, statecharts, guarded transitions, and preventing impossible states.
RecipeReact useMemo and useCallback: When to Use Them
Learn when useMemo and useCallback help React rendering, when they add work, and what React Compiler changes about manual memoization.
GuideReact State Management: Zustand, Jotai, TanStack Query
How to choose and combine React state management tools: Context API, Zustand, Jotai, and TanStack Query for server state, with patterns and a decision framework.