Lesson

Custom Hooks

10 min reading
Free Course

React Custom Hooks: Sharing Stateful Logic Cleanly

A Custom Hook is a JavaScript function whose name starts with use and that calls built-in React Hooks such as useState, useEffect, or useRef. Custom Hooks let you extract duplicated logic—like debouncing search queries, syncing localStorage, or tracking online status—into one clean, testable module.

Writing a Reusable useDebounce Hook

Each component that calls a Custom Hook receives its own isolated state and effects. Calling useDebounce inside two different search inputs never mixes their values together.

import { useEffect, useState } from 'react';

export function useDebounce(value, delayMs = 300) {
  const [debounced, setDebounced] = useState(value);

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

  return debounced;
}

export function PackageSearch() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 400);

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search packages..." />
      <p>Searching API for: {debouncedQuery}</p>
    </div>
  );
}

Naming and Design Conventions

  • Always Start with use: Naming a hook useWindowSize instead of getWindowSize enables React's ESLint rules to check hook order inside your function.
  • Return Clean Values: Return a primitive for single values (useDebounce), a tuple [value, setValue] when mirroring useState, or a named object { data, error, isLoading } when returning three or more fields.

Common Custom Hook Mistakes

  • Assuming Custom Hooks Share State Across Components: A Custom Hook shares logic, not state. If two components both call useCounter(), each component owns an independent counter. Use Context or a store to share data across components.
  • Naming Plain Helpers use...: If a function does not call any React Hooks (like formatting dates), give it a normal verb name such as formatDate rather than useFormatDate.

Frequently Asked Questions

Can a Custom Hook call another Custom Hook?

Yes. Composing smaller hooks inside larger ones—such as calling useLocalStorage inside useTheme—is one of React's strongest composition patterns.

Can Custom Hooks accept options or callbacks?

Yes. Custom Hooks are ordinary JavaScript functions, so they can accept any parameters and return any JSX-friendly values or handlers.

How do I test a Custom Hook?

Use @testing-library/react's renderHook utility to mount the hook in isolation and assert state changes cleanly.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
React Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum