Custom Hooks: reusing stateful logic

Advanced

Introduction

As components grow, the same patterns appear again and again: a value that toggles on and off, a counter with limits, a form with values and errors, a timer. Copying the useState calls and handlers into every component works, but it is repetitive and easy to get wrong. A custom Hook packages that logic into a function you can call from any component.

How it works

A custom Hook is an ordinary function whose name starts with use and that calls other Hooks:

function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = () => setOn((v) => !v);
  return [on, toggle];
}

const [dark, toggleDark] = useToggle(false);

It can take arguments and return anything. An array, like useState returns, lets callers name the parts as they like. An object, { count, add, reset }, is clearer when there are more than two parts.

The most important fact about custom Hooks: they share logic, not state. Every call runs its own useState, so useToggle called twice gives two independent values. To share data between components you still lift state up or use context; custom Hooks only save you from writing the same logic twice.

The use prefix is not just a convention. It tells React, and the linter, that the function calls Hooks, so the rules of Hooks apply to it:

  • Call Hooks only at the top level of a component or another Hook, never inside conditions, loops or nested functions.
  • Call Hooks only from components and custom Hooks, never from ordinary functions.

These rules exist because React tells Hooks apart by the order they are called in on each render. A Hook inside an if would be called on some renders and not others, and every Hook after it would get the wrong state.

A custom Hook can use effects too, which makes it the place for logic such as "keep the document title in step", "count down from a number" or "debounce a value".

Example

App.jsx
console.log output from the page shows here.

Line by line

  1. useToggle wraps one boolean state and a function that flips it, returned as an array.
  2. useCounter wraps a count with add and reset, returned as an object.
  3. App calls useToggle twice; the two calls keep separate state.
  4. The counter Hook adds its step of 5 and resets to its start.

Expected result

The preview shows "Dark mode" and "Hide details" buttons, the details line, "Score: 0" and two score buttons. "Dark mode" switches the page's class to dark without touching the details; "Hide details" hides them; +5 twice shows "Score: 10", and Reset shows "Score: 0".

In the real world

Teams build libraries of custom Hooks for their apps, such as useAuth, useCart or useMediaQuery, and popular packages publish Hooks for data fetching, forms and animation. React's own newer features, such as useId and useSyncExternalStore, are Hooks, and most React code you read will use custom Hooks heavily.

Common mistakes

  • Expecting two components using the same Hook to share data; each call has its own state.
  • Calling a Hook inside an if or a loop, breaking the order React relies on.
  • Naming a Hook without the use prefix, so the rules are not checked.
  • Writing a Hook for logic that has no state, which should be an ordinary function.

Best practices

  • Extract a custom Hook when the same stateful logic appears in two or more components.
  • Return an object when a Hook gives back more than two things.
  • Name Hooks after what they do: useToggle, useDebouncedValue, useOnlineStatus.

Summary

Custom Hooks are functions starting with use that call other Hooks to package stateful logic for reuse, returning whatever the component needs. Each call has its own state, so they share logic rather than data, and like all Hooks they must be called at the top level of components and other Hooks.

Quick check

1. Two components call useToggle(). Do they share the boolean?
2. What makes a function a custom Hook?
3. Why must Hooks not be called inside an if?
4. When should a custom Hook return an object rather than an array?

Key takeaways

  • A custom Hook is a use-function that calls other Hooks and returns what the component needs.
  • Each call gets its own state: Hooks share logic, not data.
  • Call Hooks only at the top level of components and other Hooks.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.