Components let you reuse UI. Until hooks, React had no good way to reuse the logic behind UI: the state, the subscriptions, the effect that keeps them in sync. You got mixins, then higher-order components, then render props, and each one wrapped your component in something.
A custom hook is the plain answer: a function whose name starts with use and that calls other hooks. That's the whole definition. This chapter shows why that's enough, what it does and doesn't share, and three built-in hooks that mostly exist for hook authors: useId, useSyncExternalStore and useDebugValue. It assumes you know effects and context.
The problem: the same eleven lines, twice#
Two components need to know whether the browser is online. A status bar shows it, and a save button disables itself while offline. Each one subscribes to the window's online and offline events with an effect.
The sandbox can't really drop your network, so simulate.ts fakes navigator.onLine and fires the real events. Click the buttons and watch both components.
import { useEffect, useState } from "react";
import { Rendered } from "guide-tools";
import { setOnline } from "./simulate";
function StatusBar() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const on = () => setIsOnline(true);
const off = () => setIsOnline(false);
window.addEventListener("online", on);
window.addEventListener("offline", off);
return () => {
window.removeEventListener("online", on);
window.removeEventListener("offline", off);
};
}, []);
return (
<Rendered label="StatusBar">
<p>{isOnline ? "Online" : "Disconnected"}</p>
</Rendered>
);
}
function SaveButton() {
// The same logic, copied.
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const on = () => setIsOnline(true);
const off = () => setIsOnline(false);
window.addEventListener("online", on);
window.addEventListener("offline", off);
return () => {
window.removeEventListener("online", on);
window.removeEventListener("offline", off);
};
}, []);
return (
<Rendered label="SaveButton">
<button disabled={!isOnline}>{isOnline ? "Save" : "Reconnecting..."}</button>
</Rendered>
);
}
export default function App() {
return (
<>
<button onClick={() => setOnline(false)}>Go offline</button>{" "}
<button onClick={() => setOnline(true)}>Go online</button>
<StatusBar />
<SaveButton />
</>
);
}It works. It's also the same code twice, and the next component that cares about the network will make it three. A bug fix (say, you notice the initial value can go stale) has to land in every copy.
You can't fix this with a normal helper function that returns a value, because the logic needs state and an effect, and those only work inside a component's render. What you want is a function that can call hooks.
Extract a custom hook#
So write one. Move the state and the effect into a function and return what callers need:
import { useEffect, useState } from "react";
export function useOnlineStatus(): boolean {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const on = () => setIsOnline(true);
const off = () => setIsOnline(false);
window.addEventListener("online", on);
window.addEventListener("offline", off);
return () => {
window.removeEventListener("online", on);
window.removeEventListener("offline", off);
};
}, []);
return isOnline;
}The components now say what they need (am I online?) and not how to find out. That's the real payoff, bigger than the line count: the effect is hidden behind a name that describes intent, so the component reads like a description of the UI again.
React adds no machinery here. useOnlineStatus is an ordinary function. When StatusBar renders, it calls useOnlineStatus, which calls useState and useEffect, and those two calls are recorded in StatusBar's list of hooks exactly as if you had typed them in its body. You built that list in hooks from scratch: each component's fiber keeps its hooks in call order, and a custom hook just makes some of those calls from inside another function.
Each call has its own state#
That inlining has a consequence people get wrong in interviews: custom hooks share logic, not state. StatusBar and SaveButton each have their own isOnline and their own pair of listeners. They agree only because both listen to the same browser events.
StatusBar renders and calls useOnlineStatus(). The hook's useState and useEffect run as if they were written in StatusBar's body, so they take StatusBar's hook slots 0 and 1.
If you want two components to share one value that either can change, a custom hook won't do it on its own. Lift the state to a common parent, pass it through context, or keep it outside React in a store, which is what useSyncExternalStore is for, later in this chapter.
Click "A +1" three times. What do the two lines show, and how many times has each Rendered box rendered?
import { useState } from "react";
import { Rendered } from "guide-tools";
function useCounter(initial: number) {
const [count, setCount] = useState(initial);
return { count, increment: () => setCount((c) => c + 1) };
}
function Counter({ name }: { name: string }) {
const { count, increment } = useCounter(0);
return (
<Rendered label={name}>
{name}: {count} <button onClick={increment}>{name} +1</button>
</Rendered>
);
}
export default function App() {
return (
<>
<Counter name="A" />
<Counter name="B" />
</>
);
}The rules, and why a name matters#
A custom hook follows the same two rules as any hook, for the same reason: React matches hook calls to slots by order.
- Call hooks only at the top level of a component or another hook. No hooks inside conditions, loops, or after an early
return. - Call hooks only from React function components or custom hooks, never from ordinary functions, classes or event handlers.
The use prefix is how humans and tools enforce rule 2. The ESLint plugin (eslint-plugin-react-hooks) only checks functions that look like components or hooks, and the React Compiler relies on the same convention. So the naming rule cuts both ways: if a function calls hooks, its name must start with use; if it calls no hooks, don't give it the prefix, because callers will then (wrongly) treat it as subject to the rules.
// A plain function. No hooks inside, so no "use" prefix.
function formatYear(year: number) {
return year < 1990 ? `${year} (classic)` : String(year);
}
// Calls a hook, so it is a hook.
function useNow(intervalMs: number) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(id);
}, [intervalMs]);
return now;
}Every render re-runs the hook#
A custom hook runs on every render of the component that calls it, top to bottom, with the latest props and state. That means its inputs are always fresh and it can return derived values without any extra state. It also means that any state update inside the hook re-renders the calling component. A hook that ticks every 100ms makes its caller render ten times a second, even if the caller only reads a value that changes once a minute. Hooks hide code, not cost.
Composing hooks#
Hooks call hooks, so they compose like functions do. Here's the reading list thread: a search box over the books, where the filter waits until the user stops typing for 300ms. One hook debounces any value; another builds the book search out of it.
import { useEffect, useState } from "react";
import { books } from "guide-tools";
export function useDebouncedValue<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id); // a new keystroke cancels the pending update
}, [value, delayMs]);
return debounced;
}
export function useBookSearch(query: string) {
const debouncedQuery = useDebouncedValue(query, 300);
const q = debouncedQuery.trim().toLowerCase();
const results = q ? books.filter((b) => b.title.toLowerCase().includes(q)) : books;
// Derived during render, no extra state needed.
return { results, isStale: query !== debouncedQuery };
}Type quickly and watch the render counter: every keystroke renders App (the input is controlled), and one more render lands 300ms after you stop, when the debounced value catches up. useBookSearch owns no state of its own; it borrows useDebouncedValue's and derives the rest. That's the shape most good custom hooks end up with: a little state, and the rest computed.
A few conventions worth copying:
- Return what callers read. One value: return it. Two values that callers rename (like
useState): return a tuple. More than two: return an object, so callers pick by name. - Take values, not setters, as inputs. The hook reacts to its arguments changing, just like a component reacts to props.
- Name hooks after what they do, not when they run. react.dev's advice is to avoid lifecycle wrappers like
useMount(fn)oruseEffectOnce(fn). They hide dependency bugs (the linter can't see through them) and they keep you thinking in lifecycles instead of synchronization.useChatRoom(roomId)oruseOnlineStatus()tells the reader what's being kept in sync.
useId: stable ids for accessibility#
Accessible forms need ids. A <label htmlFor> points at an input's id; aria-describedby points at a hint's id. Hard-code id="email" in a reusable <Field> component and the second <Field> on the page produces a duplicate id, and the second label now focuses the first input.
The obvious fix is a random id. It's wrong twice:
Math.random()runs on every render, so the id changes each time. (You could keep it in state or a ref, which fixes this half.)- With server rendering, the server and the browser each generate their own random number. The HTML says
id="f-k3x9a", the client's first render saysid="f-p0q2m", and hydration (attaching React to server-rendered HTML) finds attributes that don't match. A counter has the same problem as soon as rendering order differs between server and client.
useId returns an id derived from the component's position in the tree, not from randomness or render order. The server and the hydrating client walk the same tree, so they compute the same id. (A component that mounts purely on the client, with no server HTML to match, gets an id from a simple counter instead. That's safe because there's nothing to agree with, and the id is still stable for the life of the component.) The sandbox below runs real react-dom/server twice to stand in for "server" and "client".
import { useId } from "react";
import { renderToString } from "react-dom/server";
function RandomField() {
const id = "f-" + Math.random().toString(36).slice(2, 7);
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} />
</>
);
}
function StableField() {
const id = useId();
return (
<>
<label htmlFor={id + "-email"}>Email</label>
<input id={id + "-email"} aria-describedby={id + "-hint"} />
<p id={id + "-hint"}>We never share it.</p>
</>
);
}
console.log("Math.random, server:", renderToString(<RandomField />));
console.log("Math.random, client:", renderToString(<RandomField />));
console.log("useId, server: ", renderToString(<StableField />));
console.log("useId, client: ", renderToString(<StableField />));The random ids differ between the two renders. The useId ids match. Notice the pattern in StableField: call useId once per component and derive related ids with suffixes, rather than calling it three times.
The exact string (something like _R_0_ for server-rendered and hydrated components, _r_0_ for client-only ones) is an implementation detail; it has changed between React versions, so never parse it. Two more limits:
- Don't use it for list keys. Keys should come from your data.
useIdgives one id per component instance, not per item. - Several React apps on one page can pass
identifierPrefixtocreateRootorhydrateRoot(and the matching server option) so their ids can't collide.
useSyncExternalStore: subscribing the React way#
Look again at useOnlineStatus. It copies a value that lives outside React (navigator.onLine) into React state, then keeps the copy fresh with an effect. That pattern has three quiet problems:
- A gap at mount. The first render reads
navigator.onLine, but the listener is only attached after commit. If the status flips in between, the component misses it and shows a stale value until the next event. - Tearing. With concurrent rendering, React can pause a render partway and resume later. If an external value changes during that pause, components rendered before the change and after it can show different values in the same frame. React calls that a tear.
- No server value. On the server there's no
navigatorand effects don't run, so you have to guess an initial value by hand.
useSyncExternalStore (React 18+) is the built-in answer. You give it two functions, sometimes three:
subscribe(callback): start listening, callcallbackwhenever the value might have changed, and return an unsubscribe function.getSnapshot(): return the current value. React calls it during render and after every notification, and re-renders only if the result changed (compared withObject.is).getServerSnapshot()(optional): the value to use on the server and during hydration.
import { useDebugValue, useSyncExternalStore } from "react";
// Defined outside the component, so it's the same function every render.
// A new subscribe function each render would make React resubscribe each render.
function subscribe(callback: () => void) {
window.addEventListener("online", callback);
window.addEventListener("offline", callback);
return () => {
window.removeEventListener("online", callback);
window.removeEventListener("offline", callback);
};
}
export function useOnlineStatus(): boolean {
const isOnline = useSyncExternalStore(
subscribe,
() => navigator.onLine, // client snapshot: a boolean, so equal values stay equal
() => true, // server snapshot: assume online in the HTML
);
useDebugValue(isOnline ? "Online" : "Offline");
return isOnline;
}Click "Fire event, no change" a few times. React gets notified, calls getSnapshot, sees the same boolean, and skips the render: the counter doesn't move. The component holds no copy of the value at all; React reads the source of truth whenever it needs it, and if the store changes during a concurrent render, React notices and re-renders synchronously so every component shows the same value.
The rule that bites everyone: getSnapshot must return the same value when nothing changed. Return a fresh object or array on each call (() => ({ online: navigator.onLine })) and every comparison says "changed", React re-renders, calls it again, gets another new object, and loops. In development React warns "The result of getSnapshot should be cached to avoid an infinite loop". Return primitives, or return a stored object that you only replace when the data changes.
useSyncExternalStore is also how most external-store libraries, Redux and Zustand among them, connect to React. (Jotai is a deliberate exception for its default hooks; Atomic state explains the trade.) Build a store writes one from scratch, with selectors and a full look at tearing. For browser APIs like online status, media queries or window width, this hook is usually all you need.
useDebugValue#
That useDebugValue(isOnline ? "Online" : "Offline") line shows a label next to the hook in React DevTools, so when you inspect StatusBar you see OnlineStatus: "Online" instead of digging into its internals. It does nothing else, and it's only worth adding to shared hooks whose state isn't obvious from the outside. If computing the label is expensive, pass a formatter as the second argument; DevTools only calls it when someone inspects the component:
useDebugValue(date, (d) => d.toISOString());Build one: a hook that remembers#
Write useLocalStorageState(key, initialValue). It works like useState, returning [value, setValue], but:
- On mount it reads
localStorage[key](stored as JSON) and uses that if present, falling back toinitialValue. - Whenever the value changes, it writes it back as JSON.
- Two calls with different keys are independent.
The starter just wraps useState. Press Check when it works. (The sandbox's localStorage is an in-memory stand-in that resets each run.)
import { useState } from "react";
export function useLocalStorageState<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(initialValue);
// TODO: read from localStorage on mount, write on every change
return [value, setValue] as const;
}Pitfalls#
Check your understanding#
Why must a function that calls hooks start with 'use'?
Which is a good use of useId?
An interviewer asks: "What's a custom hook? If two components call the same custom hook, do they share state?"
Interview angle
A custom hook is a function whose name starts with use and that calls other hooks. It's React's way to reuse stateful logic, like a subscription or a debounced value, without wrapping components. React adds no machinery: the hook's calls are recorded in the calling component's own hook list, so every call gets its own state. Hooks share code, never state. For shared state you need lifted state, context or an external store read with useSyncExternalStore. useId gives SSR-safe ids for accessibility, and useDebugValue labels a hook in DevTools.
If two components call the same custom hook, do they share state?
Why do custom hooks have to start with use? What happens if you break the convention?
Why does useId exist? Why not Math.random() or a global counter?
Why use useSyncExternalStore instead of useState plus a subscribing useEffect?
What happens when getSnapshot returns a new object every time it's called?
What makes a custom hook well designed?
Recap#
- A custom hook is a function starting with
usethat calls other hooks. It reuses logic, and it replaced mixins, most HOCs and most render props for that job. - Hook calls inside a custom hook land in the calling component's own hook list. Each call gets its own state; nothing is shared but the code.
- Hooks compose like functions. Keep state minimal inside them and derive the rest during render; name them after what they synchronize, not lifecycle moments.
useIdgives ids derived from tree position, so the server and the client agree. Use it for accessibility links, not list keys.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)reads an external value without copying it into state, avoids tearing, and needs a stablesubscribeand a cached snapshot.useDebugValuelabels a hook in DevTools.
Sources#
- react.dev: Reusing logic with custom hooks
- react.dev: Rules of Hooks
- react.dev: useId
- react.dev: useSyncExternalStore
- react.dev: useDebugValue
- Facts checked November 24, 2026.