Custom Hook

A custom Hook is your own reusable function that bundles together React Hooks to share stateful logic between components. By convention its name starts with 'use', like useToggle or useFetch.

React

When several components need the same logic — fetching data, tracking a window size, toggling a boolean — you can extract it into a custom Hook instead of copying code. The Hook calls built-in Hooks internally and returns whatever values the components need.

Custom Hooks share logic, not state: each component that calls one gets its own independent state. The 'use' naming prefix is required so React's tooling and the Rules of Hooks apply correctly.

Syntax

function useSomething() { /* call Hooks, return values */ }

Examples

JSX — The reusable useToggle Hook manages boolean state; the button label flips between 'OFF' and 'ON' on each click.

import { useState } from "react";

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

function Switch() {
  const [on, toggle] = useToggle();
  return <button onClick={toggle}>{on ? "ON" : "OFF"}</button>;
}

Learn it in a lesson

See also

Back to the Dictionary