Composing Third-Party Hooks
You'll learn how to build domain-specific abstractions by combining established library hooks with your own custom hooks.
The Core Idea
Just as you can compose React's built-in hooks (useState, useEffect) inside custom hooks, you can also compose hooks from third-party libraries like TanStack Query, React Router, or any other library. This lets you create clean, domain-specific interfaces that hide implementation details and make your components simpler.
Think of it like a recipe: TanStack Query gives you ingredients for data fetching, React Router provides navigation ingredients, and you combine them into a signature dish tailored to your application's needs.
Why Compose Third-Party Hooks?
Library hooks are generic by design—they work for any use case. But your application has specific patterns. By wrapping library hooks in your own custom hooks, you:
- Centralize configuration: Set defaults once instead of repeating them
- Simplify component code: Hide complexity behind intuitive names
- Create domain language:
useCurrentUser()is clearer than raw query logic - Enable easy refactoring: Change the underlying library without touching every component
The Pattern
// Composing TanStack Query with custom logic
function useCurrentUser() {
const { data, isLoading, error } = useQuery({
queryKey: ['user', 'current'],
queryFn: fetchCurrentUser,
staleTime: 5 * 60 * 1000, // 5 minutes
});
return { user: data, isLoading, error };
}
// Your component stays clean
function Profile() {
const { user, isLoading } = useCurrentUser();
// ...
}
You've wrapped a third-party hook with your application's conventions, creating a reusable, testable abstraction.
Key Takeaway: Composing third-party library hooks inside your custom hooks creates domain-specific abstractions that make components cleaner and centralize configuration patterns across your app.