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

Extracting Shared Logic from Multiple Custom Hooks

Identify common patterns across custom hooks and factor them into smaller, composable hook utilities.

Extracting Shared Logic from Multiple Custom Hooks

You'll learn how to identify patterns that appear in several custom hooks and consolidate them into smaller, reusable utilities.

The Problem: Repeated Patterns Across Hooks

As you build more custom hooks, you'll notice similar logic cropping up repeatedly. Maybe multiple hooks need to track previous values, handle mounted state, or manage intervals. Just like you extract components to avoid duplication in JSX, you can extract smaller hook utilities to avoid duplication in hook logic.

Identifying Common Patterns

Look for these signs:

  • Similar useState + useEffect combinations appearing in different hooks
  • Repeated cleanup logic (like clearing intervals or removing listeners)
  • Common transformations on values before returning them

For example, if both useDebounce and useThrottle need to track whether the component is mounted to avoid state updates after unmount, that's a reusable pattern.

Creating Composable Hook Utilities

Extract the shared logic into a tiny custom hook that other hooks can call:

function useIsMounted() {
  const isMounted = useRef(true);
  
  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);
  
  return isMounted;
}

Now multiple hooks can use this instead of duplicating the pattern:

function useDebounce(value, delay) {
  const isMounted = useIsMounted();
  const [debouncedValue, setDebouncedValue] = useState(value);
  
  useEffect(() => {
    const timer = setTimeout(() => {
      if (isMounted.current) {
        setDebouncedValue(value);
      }
    }, delay);
    return () => clearTimeout(timer);
  }, [value, delay, isMounted]);
  
  return debouncedValue;
}

Think in Layers

Your hook composition can be layered: small utilities like useIsMounted → mid-level hooks like useDebounce → feature-specific hooks. Each layer focuses on one responsibility.

Key Takeaway: When you spot the same logic pattern in multiple custom hooks, extract it into a smaller composable hook utility—this reduces duplication and makes your hooks easier to maintain and test.