Skip to main content

Lesson 8 of 11

Custom Hooks - Extracting Reusable Logic

Custom hooks are the primary code-reuse mechanism in React. They extract stateful logic from components into standalone functions - making components leaner, logic testable in isolation, and patterns shareable across the codebase. Good custom hooks are the hallmark of senior React engineering.

40 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Custom Hook Patterns - Production Examples

Custom Hook Patterns - Production Examples
import { useState, useEffect, useCallback, useRef } from 'react';

// 1. useDebounce - delay a value update
function useDebounce<T>(value: T, delayMs: number): T {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(timer);
  }, [value, delayMs]);

  return debounced;
}

// Usage: search query debounced 300ms before API call
function Search() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 300);

  useEffect(() => {
    if (debouncedQuery) fetchResults(debouncedQuery);
  }, [debouncedQuery]);

  return <input value={query} onChange={e => setQuery(e.target.value)} />;
}

// 2. useLocalStorage - persistent state
function useLocalStorage<T>(key: string, initialValue: T) {
  const [value, setValue] = useState<T>(() => {
    try {
      const stored = localStorage.getItem(key);
      return stored ? (JSON.parse(stored) as T) : initialValue;
    } catch { return initialValue; }
  });

  const setStoredValue = useCallback((newValue: T | ((prev: T) => T)) => {
    setValue(prev => {
      const next = typeof newValue === 'function'
        ? (newValue as (prev: T) => T)(prev)
        : newValue;
      localStorage.setItem(key, JSON.stringify(next));
      return next;
    });
  }, [key]);

  return [value, setStoredValue] as const;
}

// 3. useOnClickOutside - close panels/modals on outside click
function useOnClickOutside(
  ref: React.RefObject<HTMLElement>,
  handler: (event: MouseEvent | TouchEvent) => void
) {
  useEffect(() => {
    function listener(event: MouseEvent | TouchEvent) {
      if (!ref.current || ref.current.contains(event.target as Node)) return;
      handler(event);
    }
    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);
    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
    };
  }, [ref, handler]);
}

// 4. useAsync - standardized async state
interface AsyncState<T> {
  data: T | null;
  loading: boolean;
  error: Error | null;
}

function useAsync<T>(asyncFn: () => Promise<T>, deps: React.DependencyList) {
  const [state, setState] = useState<AsyncState<T>>({
    data: null, loading: true, error: null,
  });

  useEffect(() => {
    let cancelled = false;
    setState({ data: null, loading: true, error: null });

    asyncFn()
      .then(data => { if (!cancelled) setState({ data, loading: false, error: null }); })
      .catch(error => { if (!cancelled) setState({ data: null, loading: false, error }); });

    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  return state;
}

Common Mistakes - Custom Hooks

  • Not prefixing with `use` - the `use` prefix is how ESLint's rules-of-hooks plugin identifies custom hooks and enforces the rules on them; without it, callers can break the Rules of Hooks
  • Returning too much from a hook - if a hook returns 10 values, it's probably doing too much; split it into focused hooks
  • Not memoizing callbacks returned from hooks - functions returned from a hook (like setStoredValue above) should be wrapped in useCallback so consumers can safely use them as effect dependencies
  • Coupling hooks to components - custom hooks that import specific components or use component-specific state should be refactored; hooks should be independent of UI
  • Not testing hooks with renderHook - custom hooks are testable in isolation using `@testing-library/react`'s `renderHook`; skipping tests on complex hooks is a common oversight

Tip

Tip

Practice Custom Hooks Extracting Reusable Logic in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Custom Hooks - Extracting Reusable Logic

Practice Task

Note

Practice Task - (1) Write a working example of Custom Hooks Extracting Reusable Logic from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Custom Hooks Extracting Reusable Logic is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • Custom hooks are the primary code-reuse mechanism in React.
  • Not prefixing with `use` - the `use` prefix is how ESLint's rules-of-hooks plugin identifies custom hooks and enforces the rules on them; without it, callers can break the Rules of Hooks
  • Returning too much from a hook - if a hook returns 10 values, it's probably doing too much; split it into focused hooks
  • Not memoizing callbacks returned from hooks - functions returned from a hook (like setStoredValue above) should be wrapped in useCallback so consumers can safely use them as effect dependencies

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/11 done