Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 64

Composing Custom Hooks

Recommended resources

Hello! Welcome to the final lesson of our module on creating reusable logic with custom hooks.

In our previous lessons, we've built a powerful toolkit of single-purpose hooks: useFetch for data retrieval, useForm for complex form management, and useLocalStorage for state persistence. Each of these encapsulates a specific piece of logic, making our components cleaner.

Today, we'll learn how to combine these building blocks. Our learning outcome is to compose multiple hooks together to build more complex custom hooks. This is a fundamental pattern in modern React development, allowing you to create high-level, domain-specific abstractions that perfectly match your application's needs. This concept is analogous to functional composition in programming, where you combine simple functions to create more powerful ones.

The Core Principle: Hooks Are Just Functions

At its heart, hook composition is simple: custom hooks are just JavaScript functions that can call other hooks. As long as you follow the Rules of Hooks (e.g., calling them at the top level of your function), you can nest them to build layers of abstraction.

Let's start with an example that directly builds on our last lesson. We created useLocalStorage to persist a value. What if we want to manage a user's authentication status, where the token is persisted but the user object is held in memory? We can compose useLocalStorage and useState to create a new, more meaningful useAuth hook.

// src/hooks/useAuth.ts
import { useState } from 'react';
import { useLocalStorage } from './useLocalStorage';

interface User {
  id: string;
  name: string;
  email: string;
}

// A simple hook for demonstration purposes
export function useAuth() {
  // 1. Compose useLocalStorage to persist the auth token
  const [token, setToken] = useLocalStorage<string | null>('authToken', null);

  // 2. Compose useState to hold the user object in memory (non-persistent)
  const [user, setUser] = useState<User | null>(null);

  const login = (newToken: string, newUser: User) => {
    setToken(newToken);
    setUser(newUser);
  };

  const logout = () => {
    setToken(null);
    setUser(null);
  };

  // 3. Return a cohesive API for managing authentication
  return { token, user, login, logout };
}

In this example, useAuth calls two other hooks internally to manage its state. To any component using useAuth, these implementation details are hidden. The component gets a clean API (token, user, login, logout) tailored specifically to authentication. This is the power of composition.


Decomposing and Re-composing Logic

A common workflow is to identify complex logic in a component, decompose it into smaller, single-purpose hooks, and then re-compose those hooks into a higher-level hook that serves the component's needs.

The following video demonstrates this pattern beautifully. It starts with a component that handles both user input and list filtering, then extracts that logic into useInput and useFilter hooks, and finally composes them into a single useSearch hook.

React Hook Patterns That Will Make You a Better Developer

This clip from the video 'React Hook Patterns That Will Make You a Better Developer' by Cosden Solutions clearly illustrates the process of composing custom hooks.

Please watch from 06:00 to 10:36. Pay close attention to how the logic within the App component is first separated into two distinct, reusable hooks and then combined into a more powerful useSearch hook that encapsulates the entire search feature.

Inspired by the video, let's create our own fully-typed version of this useSearch pattern.

First, we define our building blocks. Notice the use of useMemo in useFilteredList—this is a performance optimization we'll cover in detail in the next module, but for now, know that it prevents re-running the filter on every render unless the items or query change.

// src/hooks/useInput.ts
import { useState } from 'react';

export function useInput(initialValue: string = '') {
  const [value, setValue] = useState(initialValue);
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };
  return { value, onChange, setValue };
}

// src/hooks/useFilteredList.ts
import { useMemo } from 'react';

export function useFilteredList<T>(items: T[], query: string, filterFn: (item: T) => boolean) {
  const filteredItems = useMemo(() => {
    if (!query) {
      return items;
    }
    return items.filter(filterFn);
  }, [items, query, filterFn]);

  return filteredItems;
}

Now, we compose them into useSearch.

// src/hooks/useSearch.ts
import { useInput } from './useInput';
import { useFilteredList } from './useFilteredList';

interface Fruit {
  name: string;
}

export function useSearch(items: Fruit[]) {
  // 1. Compose useInput to manage the search query state and change handler
  const { value: query, onChange: onQueryChange, setValue: setQuery } = useInput('');
  
  // 2. Define the filtering logic
  const filterFn = (fruit: Fruit) => fruit.name.toLowerCase().includes(query.toLowerCase());

  // 3. Compose useFilteredList to get the filtered results
  const filteredItems = useFilteredList(items, query, filterFn);

  // 4. Return a single, cohesive object for the consuming component
  return {
    query,
    onQueryChange,
    setQuery,
    filteredItems,
  };
}

// In a component:
// const { query, onQueryChange, filteredItems } = useSearch(allFruits);

By composing useInput and useFilteredList, our new useSearch hook provides a complete, self-contained search feature. The component that uses it doesn't need to know about useState or useMemo; it just gets the tools it needs to render a search UI.

Test your understanding!

Imagine you have the useFetch hook from Module 4 and a useDebounce hook that takes a value and a delay, returning the debounced value.

function useDebounce<T>(value: T, delay: number): T {
  // ... implementation ...
}

How would you sketch out a useDebouncedFetch hook that takes a URL and a debounce delay, and only performs the fetch operation after the user has stopped typing the URL for a specified time?

Show answer

You would compose useDebounce and useFetch. The idea is to debounce the URL before passing it to useFetch.

import { useState } from 'react';
import { useDebounce } from './useDebounce';
import { useFetch } from './useFetch'; // Assuming this hook exists

export function useDebouncedFetch<T>(initialUrl: string, delay: number) {
  const [url, setUrl] = useState(initialUrl);

  // 1. Debounce the URL state
  const debouncedUrl = useDebounce(url, delay);

  // 2. Pass the debounced URL to useFetch
  // The useFetch hook will only re-run its effect when `debouncedUrl` changes.
  const { data, error, isLoading } = useFetch<T>(debouncedUrl);

  // Return the fetch state along with the function to update the URL
  return { data, error, isLoading, setUrl };
}

Advanced Composition: Real-World Scenarios

The composition pattern scales beautifully to handle very complex application logic. By composing hooks from React, your own custom library, and third-party libraries (like data fetching or UI libraries), you can create incredibly powerful abstractions.

Let's look at a couple of advanced, real-world examples.

1. The "Action" Hook Pattern

It's common to group all related API mutations (Create, Update, Delete) for a single data entity into one hook. This hook composes multiple data-fetching hooks (e.g., from a library like TanStack Query) to provide a unified API for all user actions.

React TypeScript Frontend Development Guide

The following code from a 'React TypeScript Frontend Development Guide' is an excellent example of an 'action' hook. It composes multiple mutation hooks from TanStack Query into a single useUserActions hook.

Study the useUserActions.ts code snippet. Notice how useCreateUser, useUpdateUser, and useDeleteUser (which are themselves custom hooks built on TanStack Query's useMutation) are all called inside useUserActions. The hook then returns a clean set of functions (createUser, updateUser, deleteUser) for the UI to call.

This useUserActions hook encapsulates not just the API calls but also concerns like loading state management and providing the currently logged-in user from context.

2. Composing for UI Logic

Composition isn't just for data and state. You can also compose hooks to manage complex UI behavior, like a notification system.

The useNotifications hook below composes the useToast hook from a UI library (like shadcn/ui) with useCallback to create a set of memoized functions for showing different types of notifications.

// From resource "React TypeScript Frontend Development Guide" (ID: [LINK](https://claude.ai/public/artifacts/25da58a3-008d-4676-989d-60d2ebaa8503))
// src/hooks/useNotifications.ts
import { useToast } from '@/components/ui/use-toast'; // A hook from a UI library
import { useCallback } from 'react';

export function useNotifications() {
  // 1. Compose the base hook
  const { toast } = useToast();

  // 2. Compose with useCallback to create stable functions
  const notifyBudgetWarning = useCallback((categoryName: string) => {
    toast({
      title: "Budget Warning",
      description: `You're close to your budget limit for ${categoryName}.`,
      variant: "destructive",
    });
  }, [toast]);

  const notifyExpenseCreated = useCallback((amount: number) => {
    toast({
      title: "Expense Added",
      description: `Expense of ${amount.toFixed(2)} has been recorded.`,
    });
  }, [toast]);
  
  // 3. Return the specialized notification functions
  return { notifyBudgetWarning, notifyExpenseCreated };
}

A component can now call notifyBudgetWarning() without needing to know anything about the underlying toast implementation.


Conclusion

You've now reached the end of our module on custom hooks, and with it, unlocked one of the most powerful patterns in React. By learning to compose hooks, you've moved beyond using individual tools to architecting sophisticated, maintainable, and highly readable systems of logic.

Key Takeaways:

  • Composition is Key: The ability to call hooks from within other hooks is a feature, not a bug. It allows for building layers of abstraction.
  • Decompose and Re-compose: A powerful workflow is to break down complex component logic into small, single-purpose hooks and then compose them back into a high-level hook that serves the component's specific needs.
  • Build Domain-Specific APIs: Hook composition allows you to create APIs that speak the language of your application's domain (e.g., useAuth, useSearch, useUserActions) rather than the language of React primitives (useState, useEffect).
  • Composition is Versatile: The pattern applies to composing built-in hooks, your own custom hooks, and hooks from third-party libraries, for managing everything from data fetching to UI logic.

Preview of the Next Module:
With your mastery of components, props, state, effects, and custom hooks, you're ready to build complex UIs. But so far, our application lives on a single "page." How do we create the experience of navigating between different views, like a dashboard, a profile page, and a settings page?

In our next module, "Client-Side Routing with React Router," we will dive into just that. We'll start by learning how to set up and configure React Router to manage navigation within your single-page application.