Custom Hooks — React

A custom hook is a function starting with use that calls other hooks, such as useState, to reuse stateful logic (logic that holds state) without copying code…

Since the useState lesson, you've used several of React's built-in hooks: useState, useEffect, useRef, useContext. Now it's your turn to make one.

A custom hook is an ordinary function whose name starts with use and that calls other hooks inside it, such as useState. With a custom hook, logic that holds state (the state plus the way to change it) is written once, then used in many components. A custom hook is like one beef curry recipe used by two cooks: the recipe is the same, but each cook uses their own pot. If cook A adds salt, cook B's pot doesn't get salty. In React, the recipe is the custom hook, each cook is a component that uses it, and each pot is that component's state.

The same logic written again and again

These two components both need a true or false value they can flip:

function Lamp({ name, initial }) {
  const [isOn, setIsOn] = useState(initial)
  const toggle = () => setIsOn((v) => !v)

  return (
    <div>
      <p>{name}: {isOn ? "ON" : "OFF"}</p>
      <button onClick={toggle}>Toggle</button>
    </div>
  )
}

function Spoiler() {
  const [isOpen, setIsOpen] = useState(false)
  const toggle = () => setIsOpen((v) => !v)

  return (
    <div>
      <button onClick={toggle}>{isOpen ? "Hide" : "Show answer"}</button>
      {isOpen && <p>The answer: a custom hook!</p>}
    </div>
  )
}

The first two lines of each component are the same, only the names differ. What if there's a bug in the way it flips? You'd have to fix it in every component that copied those lines.

Move it into a custom hook

Those two shared lines move into one function, useToggle, and both components call it:

import { useState } from "react"

function useToggle(initial = false) {
  const [value, setValue] = useState(initial)
  const toggle = () => setValue((v) => !v)
  return [value, toggle]
}

function Lamp({ name, initial }) {
  const [isOn, toggle] = useToggle(initial)

  return (
    <div>
      <p>{name}: {isOn ? "ON" : "OFF"}</p>
      <button onClick={toggle}>Toggle</button>
    </div>
  )
}

function Spoiler() {
  const [isOpen, toggle] = useToggle(false)

  return (
    <div>
      <button onClick={toggle}>{isOpen ? "Hide" : "Show answer"}</button>
      {isOpen && <p>The answer: a custom hook!</p>}
    </div>
  )
}

Every call has its own state

App shows <Lamp name="Porch" initial={true} />, <Lamp name="Kitchen" initial={true} /> and <Spoiler />. Then you click:

Action Porch Kitchen Spoiler
Start ON ON closed
Click Toggle on the Porch OFF ON closed
Click Toggle on the Porch again ON ON closed
Click Toggle on the Kitchen ON OFF closed

useToggle is called three times, so there are three separate useStates. The Kitchen stays ON when the Porch goes OFF. A custom hook shares how it works, not what's in its state. If two components must hold the same value, lift the state up to their parent (lifting state up) or use Context.

Rules for custom hooks

  1. The name starts with use: useToggle, not toggle or toggleHelper. From that prefix, React's linter (eslint-plugin-react-hooks, a program that checks your code) recognises the function as a hook, and check its rules.
  2. Call hooks at the top level. The top level means the outermost level of the component, not inside an if, a loop, or a function nested inside. This rule holds inside a custom hook too.
  3. Call hooks only from components or other custom hooks, not from ordinary functions.
  4. What it returns is up to you. An array like [value, toggle] is useful when the caller wants to pick the names. An object works too:
function useToggle() {
  const [on, setOn] = useState(false)
  const toggle = () => setOn((prev) => !prev)
  return { on, toggle }
}

const { on, toggle } = useToggle() // read back with the same names

A custom hook can hold an effect too. useWindowWidth below returns the width of the browser window, and two components use it:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth)

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth)
    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])

  return width
}

function Navbar() {
  const width = useWindowWidth()
  return <nav>{width < 600 ? "Menu" : "Home | Products | Contact"}</nav>
}

function Footer() {
  const width = useWindowWidth()
  return <footer>Screen width: {width}px</footer>
}

🎯 A custom hook, a plain function, or a component?

⚠️ Toggles with the wrong idea, the wrong value, or in the wrong place

TL;DR: A custom hook is a function starting with use that calls other hooks, such as useState, to reuse stateful logic (logic that holds state) without copying code. For example, useToggle(initial = false) keeps one boolean, makes a toggle that flips it with setValue((v) => !v), and returns [value, toggle]. Every call has its own state: if a Porch lamp and a Kitchen lamp both use useToggle, turning the Porch OFF doesn't turn the Kitchen OFF. Follow the rules of hooks: the name starts with use, it's called at the top level (not inside an if or a loop), and only from components or other hooks. What it returns may be an array or an object.

⚡ The same logic written again and again

Meaning: The components Lamp (a lamp that is ON or OFF) and Spoiler (an answer you can open and close) both keep one boolean with useState, then flip it with a toggle function. Instead of copying useState and toggle into every component, move the logic into one function.

⚡ Move it into a custom hook

Write:

function useToggle(initial = false) {
  const [value, setValue] = useState(initial)
  const toggle = () => setValue((v) => !v)
  return [value, toggle]
}

function Lamp({ name, initial }) {
  const [isOn, toggle] = useToggle(initial)

  return (
    <div>
      <p>{name}: {isOn ? "ON" : "OFF"}</p>
      <button onClick={toggle}>Toggle</button>
    </div>
  )
}

Meaning: A custom hook is a function starting with use that calls other hooks, such as useState. useToggle keeps one boolean, makes a toggle that flips it, then returns [value, toggle]. Lamp calls it and picks its own names: [isOn, toggle]. Its main benefit: reusing stateful logic (logic that holds state) without copying code.

⚡ Every call has its own state

Guess first: two Lamps, the Porch and the Kitchen, both use useToggle and both start ON. You click the Toggle button on the Porch. Does the Kitchen go OFF too?

No. Every call to useToggle has its own useState, so the Kitchen stays ON.

Meaning: A custom hook shares how it works, not what's in its state. If two components must hold the same value, lift the state up to their parent.

What you will learn