Course contentsShow
← React
Lesson 989 of 2,39625. Custom HooksFree lesson

Building Higher-Order Hooks

Create custom hooks that accept other hooks as parameters or return hook-generating functions for advanced reusability.

Building Higher-Order Hooks

What you'll learn: How to create custom hooks that accept other hooks as parameters or return hook-generating functions for maximum reusability.

The Core Idea

Just like you can compose multiple hooks inside a custom hook, you can take this a step further: build hooks that work with other hooks as their inputs or outputs. This creates a layer of abstraction where your custom hooks become more flexible and powerful.

Think of it like building a tool that modifies other tools. A higher-order hook might accept a custom hook as a parameter and enhance its behavior, or it might return a new hook function based on configuration you provide.

Hook as Parameter

You can create a custom hook that takes another hook function and wraps it with additional logic:

function useWithLogging(useHook, hookName) {
  console.log(`Calling ${hookName}`);
  const result = useHook();
  console.log(`${hookName} returned:`, result);
  return result;
}

// Usage
function MyComponent() {
  const isOpen = useWithLogging(() => useToggle(false), 'useToggle');
  // Logs every time useToggle is called
}

Hook-Generating Function

You can create a function that returns a custom hook based on parameters:

function createUseLocalStorage(key) {
  return function useSpecificLocalStorage() {
    // Now this hook is bound to a specific key
    return useLocalStorage(key);
  };
}

// Create specialized hooks
const useUserName = createUseLocalStorage('userName');
const useTheme = createUseLocalStorage('theme');

This pattern lets you generate tailored hooks from a common template, avoiding repetition while maintaining the hook rules.

Key Takeaway: Higher-order hooks let you abstract patterns about hooks themselves, creating hook enhancers (accepting hooks as parameters) or hook factories (returning configured hooks) for advanced reusability scenarios.