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>
)
}
useToggleis just an ordinary function. What makes it different: its name starts withuse, anduseTogglecalls a hook (useState) inside.initial = falseis a default parameter value:useToggle()with no argument starts atfalse.setValue((v) => !v)flips the latest value: true becomes false, false becomes true. So a second click always brings it back to where it started.return [value, toggle]returns a pair, exactly likeuseState. The component that calls it is free to name them:[isOn, toggle]in Lamp,[isOpen, toggle]in Spoiler.- The main benefit: reusing stateful logic, logic that holds state, without copying code. A bug in
togglegets fixed in one place.
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
- The name starts with
use:useToggle, nottoggleortoggleHelper. 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. - 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. - Call hooks only from components or other custom hooks, not from ordinary functions.
- 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>
}
useEffectadds a listener for theresizeevent, only once, on mount (its dependency array is[]). Each time the window changes size,setWidthstores the new width.- The function returned from the effect is the cleanup: it removes the listener when the component leaves the page. Without cleanup, the old listener keeps running.
- At a width of 400 pixels,
NavbarshowsMenu, andFootershowsScreen width: 400px. Each component has its ownwidthand its own listener.
🎯 A custom hook, a plain function, or a component?
- Needs state or an effect (open and close, a timer, localStorage): a custom hook.
- Only calculates or formats (a total price, the format
$15.00): a plain function, nouseneeded. - A piece of the screen used again (a button with the same style): a component.
- Logic that used to be shared through a HOC (
withSomething) is now almost always written as a custom hook, because a custom hook adds no extra component layer.
⚠️ Toggles with the wrong idea, the wrong value, or in the wrong place
- Thinking the state is shared. Two components calling
useToggleeach have their own state. - Setting a fixed value instead of flipping.
setValue(false)can only switch it off. The second click doesn't switch it on again. Flip the previous value withsetValue((v) => !v). - The wrong starting value.
useToggle(false)makes the first textOFF. If it has to start atON, calluseToggle(true). - A hook inside an
if.if (active) { useToggle() }breaks the rules of hooks: the order of hooks has to be the same on every render.
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.