Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 132 ยท Hooks

Custom Hooks

Learn to write React custom hooks - extract logic from components, share behavior (not state), build useToggle, useDebounce and a fetch-like hook, compose hooks and decide hooks vs utilities.

Sooner or later two components need the same behavior: a toggle that opens and closes, a value that settles after the user stops typing, a piece of state that is saved somewhere. You could copy the useState and useEffect calls from one component to the other, but copied code drifts apart and hides what the component is really about.

A custom hook is the React answer. It is an ordinary JavaScript function whose name starts with use and which calls other hooks. You move the stateful logic out of the component, give it a name, and call it wherever you need it. This lesson shows how to extract one, what "sharing" really means, and how to decide whether something deserves to be a hook at all. It builds on useState, useEffect and useReducer.

A hook is a function that calls hooks

There is no special API for custom hooks. If a function calls useState, useEffect, useContext or any other hook, and its name begins with use, it is a custom hook. The use prefix is not decoration: React's linter relies on it to know that the function must follow the rules of hooks, and readers rely on it to know that the function may hold state.

Start with the smallest useful example. A component that shows or hides a panel:

JSX
function Panel() {
  const [isOpen, setIsOpen] = useState(false);
  const toggle = () => setIsOpen((open) => !open);
  // ...
}

Move those two lines into a function, return what the component needs, and you have a hook:

JSX
function useToggle(initialValue = false) {
  const [isOn, setIsOn] = useState(initialValue);
  const toggle = () => setIsOn((value) => !value);
  return [isOn, toggle];
}
useToggle shared by three components

Open the first panel and the second stays closed. The hook is shared, but the state is not.

Sharing logic, not state

This is the idea beginners most often get wrong. Calling useToggle() in two components does not make them share one boolean. Each call to a hook creates its own independent state, exactly as if you had pasted the useState line into each component. A custom hook shares the recipe, never the value.

You can prove it by calling the same hook twice in one component and checking that the two results are separate.

Each call gets its own state

The console shows one line per hook call on every render. Press "+1" next to Apples and only the Apples count moves, even though both counters come from the same function. If you need several components to read and write the same value, that is a job for lifting state up or context, and a custom hook can still wrap the useContext call.

A hook re-runs on every render of the component that calls it, because it is just code inside that component. Its state lives in the component, not in the hook function.

Extract by purpose, not by line count

Do not make a hook out of every pair of lines. Make one when you can name what the code does in plain words: "track whether the user is online", "debounce a value", "keep a draft". If the best name you can find is useStuff or useHandlers, the code probably belongs in the component.

A good extraction has three effects. The component reads like a description of the screen. The logic can be reused. And the logic can be understood and fixed in one place. Notice what happens to a component when the logic moves out.

Before:

JSX
function SearchBox() {
  const [text, setText] = useState('');
  const [debounced, setDebounced] = useState('');
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(text), 200);
    return () => clearTimeout(timer);
  }, [text]);
  // ...
}

After:

JSX
function SearchBox() {
  const [text, setText] = useState('');
  const debounced = useDebounce(text, 200);
  // ...
}

The second version tells you what the component does. To learn how debouncing works, you open one small function.

Example: useDebounce

Debouncing waits until a value has stopped changing before acting on it. It is useful for search boxes, where you do not want to run a query on every keystroke. The hook stores a copy of the value, and an effect schedules an update after a delay. The cleanup cancels the pending update whenever the value changes again, so only the last change survives.

useDebounce on a search box

Type "ap" quickly: "Typed" updates on each key, while "Searched for" lags behind by a quarter of a second and then jumps once. The hook has no idea it is used for search; it only knows about a value and a delay, which is exactly why it is reusable.

Example: a hook that wraps a storage-like API

A classic custom hook is useLocalStorage, which behaves like useState but remembers the value. Our sandboxed editor has no localStorage, so here is a version that talks to any object with getItem and setItem, backed by a plain in-memory Map. The hook is identical to the real one apart from the backing store.

A useStoredState hook with an in-memory store

Three details are worth copying. The initial value is read with a lazy initializer (useState(() => ...)), so the store is read once, not on every render. The value is JSON-encoded so it can hold objects and arrays. And the effect lists both key and value as dependencies, so it saves again when either changes. In a real browser you would replace store with window.localStorage and add a try/catch, because storage can be blocked or full.

Example: a fetch-like hook with loading and error

Data loading follows a pattern: start, wait, then either a result or an error. A hook can own that pattern so components just read three values. Since the sandbox has no network, this hook takes any function that returns a promise; we pass one that simulates a server with setTimeout.

useAsync with a simulated server

The ignore flag in the cleanup protects against a classic race: click "User 2" and then "User 1" quickly, and a slow answer for user 2 must not overwrite the newer result. Cleanup runs before the next effect, so the stale promise is ignored. Read cleanup, subscriptions and timers for the full story.

This hook is a teaching tool. For production data loading you want caching, deduplication, retries and refetching, which is why most apps use a server-state library or a framework instead of hand-writing useAsync. See fetching data.

Composing hooks

Hooks can call other hooks, so small hooks combine into bigger ones. A search hook might use useDebounce for the delay and useAsync for the request. Each piece stays testable and easy to explain.

A hook built from two hooks

The component sees one object with everything it needs; behind it three hooks cooperate. Notice that useSearchablePages returns a new object every render. That is fine here. If a returned object or function must keep a stable identity (for example because a consumer lists it as an effect dependency), wrap it with useMemo or useCallback, see useMemo and useCallback.

A small library of custom hooks

Teams keep a folder of small hooks that solve the same problems again and again. Here are six worth knowing, each in a few lines. Reading them is a good exercise in the rules of hooks: every one is just state, refs and effects arranged with a clear name.

useInterval and useTimeout

setInterval inside useEffect has a classic bug: if the callback uses state or props, either the interval is recreated on every render (when you list the callback as a dependency) or it uses stale values (when you do not). The fix is to keep the latest callback in a ref and run the timer once:

JSX
function useInterval(callback, delay) {
  const saved = useRef(callback);
  useEffect(() => { saved.current = callback; });      // always the latest callback

  useEffect(() => {
    if (delay === null) return;                        // null pauses the timer
    const id = setInterval(() => saved.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

useTimeout is the same with setTimeout and clearTimeout. Passing null as the delay pauses it, which makes "pause/resume" a one-line state change. useEffectEvent is the built-in way to express the same "latest callback" idea.

useWindowSize (and orientation)

Window size is an external value that changes over time: subscribe in an effect, clean up on unmount, and remember to read the initial value. Orientation is just a comparison of the two numbers:

JSX
function useWindowSize() {
  const read = () => ({ width: window.innerWidth, height: window.innerHeight });
  const [size, setSize] = useState(read);
  useEffect(() => {
    const onResize = () => setSize(read());
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return { ...size, orientation: size.width >= size.height ? 'landscape' : 'portrait' };
}

For a single breakpoint, matchMedia with useSyncExternalStore is leaner than tracking the pixel size, because it re-renders only when the answer flips.

useUndoState

useReducer makes history easy: keep past, present and future, and let actions move between them.

JSX
function undoReducer(state, action) {
  switch (action.type) {
    case 'set':
      return { past: [...state.past, state.present], present: action.value, future: [] };
    case 'undo':
      if (state.past.length === 0) return state;
      return { past: state.past.slice(0, -1), present: state.past.at(-1), future: [state.present, ...state.future] };
    case 'redo':
      if (state.future.length === 0) return state;
      return { past: [...state.past, state.present], present: state.future[0], future: state.future.slice(1) };
    default:
      return state;
  }
}

function useUndoState(initial) {
  const [state, dispatch] = useReducer(undoReducer, { past: [], present: initial, future: [] });
  return {
    value: state.present,
    set: (value) => dispatch({ type: 'set', value }),
    undo: () => dispatch({ type: 'undo' }),
    redo: () => dispatch({ type: 'redo' }),
    canUndo: state.past.length > 0,
    canRedo: state.future.length > 0,
  };
}

A new set clears future, exactly like a text editor: once you type after undoing, the old redo path is gone.

useCopyToClipboard

navigator.clipboard.writeText is async and can fail (insecure context, permission denied, or this sandbox). A good hook reports both results and resets the "copied" flag so UI can show a short confirmation:

JSX
function useCopyToClipboard(resetMs = 1500) {
  const [status, setStatus] = useState('idle');          // 'idle' | 'copied' | 'failed'
  const copy = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      setStatus('copied');
    } catch {
      setStatus('failed');
    }
  };
  useEffect(() => {
    if (status === 'idle') return;
    const id = setTimeout(() => setStatus('idle'), resetMs);
    return () => clearTimeout(id);
  }, [status, resetMs]);
  return [status, copy];
}

useForm

A tiny form hook holds the values, an onChange that works for any field with a name, and a reset:

JSX
function useForm(initialValues) {
  const [values, setValues] = useState(initialValues);
  const handleChange = (e) => {
    const { name, type, value, checked } = e.target;
    setValues((current) => ({ ...current, [name]: type === 'checkbox' ? checked : value }));
  };
  const reset = () => setValues(initialValues);
  return { values, handleChange, reset, setValues };
}

It is deliberately minimal. When you need validation, touched flags and submit handling, move to a library (see React Hook Form with Zod) rather than growing this hook.

All six at work

useInterval, useWindowSize, useUndoState, useCopyToClipboard and useForm

The timer keeps counting correctly although the callback reads fresh state every second, because it goes through the ref. Type a few characters, press Undo twice and Redo once to see the history move. In the sandbox the Copy button reports that the clipboard is unavailable, which shows why the hook returns a failed status instead of assuming success.

Designing a good hook API

A hook is a small API, so design it like one.

  • Return what callers need, in a shape that fits. A pair works for "value and setter" ([value, setValue]), and callers can rename it freely. Three or more values read better as an object ({ status, data, error }).
  • Take arguments, not globals. Pass the key, the delay or the loader function in, so the hook can be reused with different inputs.
  • Re-run when inputs change. If an argument changes, the effect inside should respond to it. List arguments as dependencies instead of silencing the linter.
  • Keep one job. A hook that tracks the mouse, loads a user and plays a sound should be three hooks.
  • Name it for what it returns or does. useOnlineStatus, useDebounce, useFormField.
  • Do not wrap lifecycle moments. Hooks like useMount(fn) or useUpdate(fn) hide the dependency list and fight React. Describe what to synchronize instead.

Testing hooks

A custom hook cannot be called outside a component, so you test it from one. The simplest approach is a tiny test component that calls the hook and prints what it returns; testing libraries offer a renderHook helper that does exactly this. If the logic is pure (a reducer, a function that formats a value), pull it out and test it as a plain function with no React at all, as covered in useReducer and reducers. The later lesson testing hooks, reducers and custom logic builds a runnable harness.

Hooks versus plain utilities

Not everything shared should be a hook. Ask one question: does this code need React features such as state, effects, context or refs?

Code Use
formatPrice(cents), slugify(text) A plain function, no use prefix
Reading a value from props and computing something A plain function or inline code
Tracking window size, online status, a timer A custom hook
State plus handlers that belong together A custom hook (or a reducer)

If a function does not call any hook, do not name it useSomething. The name would promise state that is not there and force callers to obey hook rules for no reason. The reverse also holds: if it calls hooks, it must start with use.

Common mistakes

  • Expecting shared state. Two components calling the same hook have separate state. Use context or lift state if you need one source of truth.
  • Hiding dependency problems. Calling useEffect inside a hook with an empty array "to make it run once" works until an argument changes and the hook goes stale.
  • Over-abstracting too early. Wait until you see the same logic twice, or until a component becomes hard to read.
  • Conditional calls. A custom hook is still a hook: call it at the top level, never inside an if, loop or callback.
  • Returning unstable values by accident. New objects and functions on every render are fine until they feed a memoized child or an effect dependency.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two different components both call useToggle(). What do they share?

    A custom hook shares logic, not state. Every call to useState inside it creates state belonging to the component that called the hook.
  2. 2. Which function should NOT be named with a use prefix?

    The use prefix signals that a function calls hooks and must follow the rules of hooks. A pure formatting function should stay a plain function.
  3. 3. Why does useDebounce return a cleanup function from its effect?

    Each change schedules a new timer. The cleanup clears the previous one first, so a timer only fires if no newer change replaced it.
  4. 4. Where should you put logic that is pure and needs no state or effects?

    Pure logic does not need React. A plain function is simpler, reusable anywhere, and trivial to test.
  5. 5. What is the main purpose of the ignore flag in the useAsync hook?

    When the inputs change, cleanup sets ignore to true for the old effect, so a slow earlier response cannot overwrite the newer state.

Summary

  • A custom hook is a function whose name starts with use and which calls other hooks.
  • Hooks share logic, never state: every call gets its own state inside the calling component.
  • Extract a hook when you can name its purpose, not just to shorten a component.
  • Hooks compose: small hooks like useDebounce and useAsync build bigger ones.
  • Design hooks as small APIs: take inputs as arguments, return a fitting shape, keep one job.
  • Use plain functions for logic that needs no state or effects, and test hooks through a component or renderHook.

Next: The Rules of Hooks and Common Hook Errors