Sub topic 2
What a custom hook is
This chapter assumes you know function components and JSX, useState and useEffect basics, and modern JavaScript (arrow functions, destructuring, closures). It also assumes you have read the Rules of Hooks in the previous chapter. Those rules decide where a custom hook may be called, so this chapter refers back to them.
The definition
A custom hook is a JavaScript function that meets two conditions:
- Its name starts with
use, followed by a capital letter, as inuseToggleoruseOnlineStatus. - It calls at least one other hook, either a built-in hook such as
useStateor another custom hook.
That is the whole definition. You do not register a custom hook with React, and it has no special base class or wrapper. React never sees your hook as a separate thing. It only sees the built-in hooks that run, in order, while a component renders.
The smallest useful example
This hook wraps useState for a boolean that flips between true and false:
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}useState(initial)stores the boolean.useCallbackkeeps the sametogglefunction between renders, so passing it to a child component does not cause needless re-renders. Later chapters cover stable function references in detail.- The function updater
(value) => !valuereads the newest state. That is why the empty dependency array[]is correct here. - The hook returns a two-item array, so the caller can pick any names when destructuring.
A component uses it like any built-in hook:
import { useToggle } from './useToggle';
export function Disclosure({ title, children }) {
const [open, toggleOpen] = useToggle();
return (
<section>
<button onClick={toggleOpen}>
{open ? 'Hide' : 'Show'} {title}
</button>
{open && <div>{children}</div>}
</section>
);
}What happens when a component calls a custom hook
A custom hook is not a separate unit that React runs on its own. Calling useToggle() inside Disclosure runs the hook's code during the component's render. The useState and useCallback calls inside it become hook calls of Disclosure itself. The result is the same as pasting those lines into the component body.
React keeps a list of hook slots for each component instance, in the order the calls happen. On every render it matches the first call to the first slot, the second call to the second slot, and so on. This order-based matching is the reason the Rules of Hooks exist, and it applies to custom hooks too. A custom hook that calls three built-in hooks adds three slots to its caller.
Two consequences follow:
- A custom hook has to be called while a component or another hook is rendering. It cannot be called from an event handler, a timer callback, or a plain function.
- Because the hook's state lives in the calling component's slots, each component that calls the hook gets its own state. The state-isolation chapter covers this further.
Why the `use` prefix matters
The prefix is a convention, and React itself does not check it at runtime. The tools around React depend on it. The eslint-plugin-react-hooks package treats any function named use plus a capital letter as a hook. It then enforces the Rules of Hooks inside that function and at every place that calls it. If you name the same function toggleHelper, the linter stops checking it, and a conditional hook call inside it goes unnoticed until it breaks at runtime.
The prefix also tells readers that the function may hold state and that its call position matters.
| Function | Calls hooks? | Name it with `use`? |
|---|---|---|
| `formatPrice(amount)` | No | No. It is a plain function. |
| `useToggle(initial)` | Yes, `useState` and `useCallback` | Yes. |
| `getTheme()` that calls `useContext` inside | Yes | Rename it to `useTheme`. The current name hides a hook call. |
| `useFormatPrice(amount)` that only does math | No | Rename it to `formatPrice`. A `use` prefix on a non-hook is misleading. |
The last row is the reverse mistake. Do not add use to a function that calls no hooks. Callers would think the function has position restrictions that it does not have, and they could not use it in a loop or after an early return.
Parameters and return values are ordinary JavaScript
A custom hook can take any arguments and return anything: a value, an array, an object, a function, or nothing. React places no constraints on either.
import { useEffect } from 'react';
export function useDocumentTitle(title) {
useEffect(() => {
document.title = title;
}, [title]);
}useDocumentTitle returns nothing and exists only for its effect. It re-runs whenever title changes. A hook that only runs an effect and returns nothing is common and fine.
Two habits help from the start:
- When a hook returns one or two values that callers will usually rename, return an array, as
useStatedoes. - When it returns three or more values, or values that callers use selectively, return an object so callers can pick fields by name.
Parameter and return design gets its own chapter.
Where custom hooks can and cannot be called
Custom hooks follow the same rules as built-in hooks. Call them at the top level of a function component or of another custom hook.
import { useToggle } from './useToggle';
// Wrong: a plain helper function is not a component or a hook.
function openPanel() {
const [open, toggle] = useToggle();
return open;
}
// Wrong: conditional call changes the slot order between renders.
function Sidebar({ collapsible }) {
if (collapsible) {
const [open, toggle] = useToggle();
}
return <nav />;
}
// Wrong: a hook inside an event handler runs outside of render.
function SaveButton() {
return <button onClick={() => useToggle()}>Save</button>;
}All three calls break the Rules of Hooks. React reports the first and third as "Invalid hook call". The conditional call in Sidebar may fail more quietly. The slot order changes between renders, so state ends up attached to the wrong hook or React throws a hook-count error. The linter flags all three, but only because the name starts with use.
The fix is to call the hook unconditionally and put the condition in the logic that uses its result:
import { useToggle } from './useToggle';
function Sidebar({ collapsible }) {
const [open, toggle] = useToggle();
return collapsible && !open ? <nav>Collapsed</nav> : <nav>Full menu</nav>;
}Common errors
- Missing prefix. The hook works, but the linter cannot protect it or its callers. Rename the function and update the imports.
- Prefix on a non-hook. The function calls no hooks, so callers carry restrictions for nothing. Rename it to a plain verb.
- Calling a hook from a regular function. If you need the logic in a callback, call the hook in the component, keep the result in a variable, and use that variable in the callback.
- Expecting shared state. Two components that call
useToggledo not see each other's value. A custom hook shares code, not state. To share one value, lift the state up or use context. - Using hooks in class components. Hooks work only in function components and other hooks. Wrap the hook in a small function component, or migrate the class.
- Unclear first versions. If you cannot say in one sentence what the hook does, you probably extracted too early. The next chapter shows how to extract logic that really repeats.
Exercises
Exercise
Which of these functions should be named with a use prefix, and why? (a) calculateTotal(items), which adds up prices. (b) currentUser(), which calls useContext(UserContext) and returns the result. (c) useRandomId(), which returns Math.random().toString(36) and calls no hooks.
Show answer
Only (b). It calls a hook, so it is a custom hook and should be renamed useCurrentUser. That lets the linter enforce the Rules of Hooks for it and for its callers. (a) is a plain function with no hooks, so it should keep its name. (c) calls no hooks, so the use prefix is misleading and it should be renamed, for example randomId. (In practice, a random id created during render would also change on every render, so it needs useId or useState to be stable.)
Exercise
A teammate writes this and reports "Invalid hook call". What is wrong, and how do you fix it? function Counter() { const handleClick = () => { const [count, toggle] = useToggle(); toggle(); }; return <button onClick={handleClick}>Toggle</button>; }
Show answer
The component calls useToggle inside an event handler, which runs after render and not during it. React can only match hook calls to slots while rendering. Move the call to the top level of Counter: const [on, toggle] = useToggle();. Then use toggle inside handleClick, or pass it straight to onClick.