Lesson 15 of 37Effects and beyond
Custom Hooks
Extract stateful logic into your own use-functions, and understand the rules of hooks that make them work.
Once you write the same useState plus useEffect combination in three components (online status, a debounced input, a value saved to storage), you want to name it once and reuse it. Custom hooks are how React apps share logic the way components share UI. Most real codebases have a hooks/ folder, and "write a useDebounce" is a favourite live-coding interview task.
A hook is just a function that calls hooks
A custom hook is a function whose name starts with use and that calls other hooks. That is the whole definition. There is no registration and no special API.
Notice the two toggles do not interfere. A custom hook shares logic, not state. Each call to useToggle gets its own useState slot, exactly as if you had written useState twice by hand.
Hooks that wrap the outside world
Custom hooks shine when they hide an effect. Here useOnline subscribes to the browser's online and offline events. The component that uses it reads like a sentence and knows nothing about listeners.
Turn off your Wi-Fi and the preview updates. (For subscriptions like this, React also ships useSyncExternalStore, which handles some concurrent-rendering edge cases. The effect version is fine to learn on.)
The next one is the hook you will write in the challenge. useDebounce returns a value only after it has stopped changing for a while, so a search box does not filter or fetch on every keystroke.
And useLocalStorage has the same shape as useState but persists the value. Storage can throw (private browsing, full quota, sandboxed iframes like this preview), so a good hook catches errors and falls back to plain state:
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
try {
const raw = localStorage.getItem(key);
return raw === null ? initialValue : (JSON.parse(raw) as T);
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// storage unavailable: keep working in memory
}
}, [key, value]);
return [value, setValue] as const;
}The rules of hooks
There are two rules, and the linter (eslint-plugin-react-hooks) enforces both:
- Only call hooks at the top level of a component or custom hook. Never inside conditions, loops, nested functions, or after an early
return. - Only call hooks from React functions: components and custom hooks, not plain helper functions or class methods.
Why? Hooks have no names. React does not know that your first useState is "name" and the second is "age". It keeps a list of hook slots for each component instance and hands them out in call order: the first hook call gets slot 1, the second gets slot 2. Under the hood that list is a linked list attached to the component's fiber.
Render 1: the first useState call creates slot 1 and stores "Ada".
function Profile({ userId }: { userId: string | null }) {
const [tab, setTab] = useState("posts"); // A
if (!userId) return <p>Sign in</p>;
const user = useUser(userId); // B
const total = useMemo(() => count(user), [user]); // C
return <Tabs value={tab} onChange={setTab} />;
}How many hook slots does one SearchBox instance use?
function useDebounce(value, delay) {
const [d, setD] = useState(value);
useEffect(() => { /* timer */ }, [value, delay]);
return d;
}
function SearchBox() {
const [query, setQuery] = useState("");
const debounced = useDebounce(query, 300);
const inputRef = useRef(null);
return <input ref={inputRef} />;
}Naming and design
- Start with
use. It tells readers (and the linter) that the function may call hooks and must follow the rules.useOnline,useDebounce,useCart. - Do not prefix plain functions with
use. A helper that calls no hooks, likeformatPrice, should stay a normal function so it can be called anywhere, including in conditions. - Name it after the purpose, not the mechanics.
useChatRoom(roomId)beatsuseWebSocketEffect. When a component readsconst isOnline = useOnline(), the effect is an implementation detail. - Return what callers need. A tuple (
[value, setValue]) for useState-like hooks, an object ({ data, error, isLoading }) when there are many fields.
You notice two components with the same online-status logic. Put the refactor in order.
- Tap the steps below in the right order.
Hooks that return stable APIs
A hook is a small library, and its callers will put what it returns into dependency arrays, pass it to memo children, and hand it to context. If a hook returns a new function or object on every render, every one of those consumers sees a "change" every time, even when nothing changed. Effects re-run, memoized children re-render, and a team ends up chasing bugs that start in a hook they never read.
The rule for a hook author: anything that does not need to change should keep its identity.
- Setters from
useStateanddispatchfromuseReducerare already stable. Return them as they are. - Functions you build should be wrapped in
useCallback, with honest dependencies. Using the updater form (setCount((c) => c + 1)) often lets the dependency list be empty. - A returned object should be built in
useMemo, or split so the stable part (actions) is separate from the changing part (values).
Click Add one several times. Controls logs once, on mount, because actions is the same object on every render. Delete the useMemo (return a plain object literal) and it logs on every click.
With the React Compiler turned on, the compiler inserts this memoization for you, including inside custom hooks. You still need to know the rule: the compiler only memoizes code that follows the rules of React, and libraries you publish may run in apps without it. For a callback that must always see the latest props but should never trigger an effect, the answer is useEffectEvent, which you met in Effect Events and Activity.
useCart() hook returns { items, addItem }, where addItem is a plain arrow function defined in the hook. A component runs useEffect(() => { prefetch(addItem); }, [addItem]). What happens?useSyncExternalStore: the right way to subscribe
The useOnline hook earlier stored the browser's state in React state and kept it in sync with an effect. It works, but it has two weak spots. The first render reads navigator.onLine once and could miss a change that happens before the effect subscribes. And during concurrent rendering, different parts of the tree can briefly read different values (React calls this tearing).
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?) is the hook React built for any value that lives outside React: browser APIs, a store library, a WebSocket cache.
subscribe(callback)starts listening and returns an unsubscribe function. Your source callscallbackwhenever the value may have changed.getSnapshot()returns the current value. React calls it during render and after every notification, and re-renders only if the result changed byObject.is.getServerSnapshot()returns the value to use during server rendering and hydration.
Resize your browser window until the preview gets narrow and the layout line flips. There is no useState and no useEffect; the browser is the single source of truth.
Two mistakes produce real bugs:
getSnapshotmust return the same value when nothing changed. If it builds a new object each call (() => ({ width: window.innerWidth })), every call looks like a change, React re-renders, calls it again, sees another change, and stops with "Maximum update depth exceeded". Return primitives, or cache the object and only replace it when the data really changes.subscribeshould be stable. An inline function, as inuseMediaQueryabove, makes React unsubscribe and resubscribe on every render. That is cheap for one media query and wasteful for a WebSocket. Define it outside the component, or wrap it inuseCallbackkeyed on its inputs (queryhere).
useSyncExternalStore(subscribe, () => ({ x: window.scrollX, y: window.scrollY })). The page crashes on first render. Why?Library-quality hooks: SSR safety
Hooks that only ever run in a client-side app can touch window freely. The moment your hook runs in Next.js, Remix, or any server-rendered app, it runs on the server first, where there is no window, localStorage, or matchMedia. A hook that is safe there follows three rules.
Do not read browser globals during render. useState(() => localStorage.getItem("theme")) throws on the server. Reading browser state belongs in getSnapshot with a getServerSnapshot fallback, or in an effect.
Do not branch render output on typeof window. It does not throw, but the server renders one thing (window is undefined) and the browser's first render, during hydration, renders another. React reports a hydration mismatch and throws away the server HTML for that part of the tree. The first client render must produce the same output as the server; update to the real value afterwards. useSyncExternalStore does exactly this: during hydration it uses getServerSnapshot, then re-renders with getSnapshot if the values differ.
Generate ids with useId. A hook that counts up a module-level variable for aria-describedby ids produces different numbers on server and client. useId() gives an id that matches on both.
For a whole subtree that cannot render on the server at all (a canvas editor, a map that needs window at import time), React 19.3 added browser() in react-dom. Calling use(browser()) inside a <Suspense> boundary tells server rendering to stop there and send the fallback; the browser renders the real content. It replaces the old trick of a mounted state flag set in an effect. It must sit inside a Suspense boundary, or the server render fails. Check the React docs for the exact behaviour in your version.
import { Suspense, use } from "react";
import { browser } from "react-dom";
function MapCanvas() {
use(browser()); // server: render the fallback instead; browser: carry on
return <div ref={(node) => { mountMap(node!); }} />;
}
export function ClientOnlyMap() {
return (
<Suspense fallback={<div className="map-skeleton" />}>
<MapCanvas />
</Suspense>
);
}A useful checklist before you publish a hook to a shared package: no browser globals during render; a server snapshot for every external value; stable returned functions; cleanup for every subscription; and a clear error if a required provider is missing.
Testing hooks with renderHook
Most hooks are best tested through a component that uses them, because that is how users meet them. Hooks that act as a small library, shared across a codebase, deserve their own tests. Testing Library's renderHook mounts a hidden test component that calls your hook and gives you its latest return value.
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { useDebounce } from "./useDebounce";
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("only updates after the value stops changing", () => {
const { result, rerender } = renderHook(({ value }) => useDebounce(value, 300), {
initialProps: { value: "a" },
});
expect(result.current).toBe("a");
rerender({ value: "ab" });
act(() => vi.advanceTimersByTime(200));
expect(result.current).toBe("a"); // not yet
rerender({ value: "abc" }); // resets the timer
act(() => vi.advanceTimersByTime(300));
expect(result.current).toBe("abc");
});The pieces that matter:
result.currentis the latest return value. Read it after each step; do not destructure it once at the top, or you keep the first render's value.rerender(newProps)calls the hook again with new arguments, which is how you test dependency changes.- Wrap anything that updates state outside React's own events (timers, resolving promises, calling a returned setter) in
act(), so React finishes the update before you assert. Async work usesawait act(async () => ...)orwaitFor. - A hook that needs a provider takes a
wrapperoption:renderHook(() => useCart(), { wrapper: CartProvider }). Testing React shows how to share one wrapper across a test suite.
renderHook lives in @testing-library/react itself. The old separate package @testing-library/react-hooks is for React 17 and earlier; delete it when you upgrade.
Put the steps of a useDebounce test with fake timers in order.
- Tap the steps below in the right order.
Debounced search with useDebounce
Write a custom hook useDebounce(value, delay) that returns value only after it has stopped changing for delay milliseconds. Use it to build a search box over a local list.
- A text input (
type="text"). - A
<ul>with one<li>per matching fruit (case-insensitiveincludes). - With an empty query, show all six fruits.
- The list updates 300 ms after typing stops, not on every keystroke.
- When nothing matches, show
No matchesinstead of the list items.
FRUITS = Apple, Apricot, Banana, Cherry, Grape, Mango
"ap" → Apple, Apricot, GrapeA useLocalStorage theme toggle
Write useLocalStorage(key, initialValue), a hook with the same shape as useState that also saves the value to localStorage as JSON and reads it back on the first render. Then use it for a theme setting.
- A paragraph shows
Theme: light(the initial value). - A Toggle theme button switches between
lightanddark.
Storage can fail: private browsing, a full quota, or a sandbox like this preview, where touching localStorage throws. Wrap every read and write in try/catch so the hook still works as plain state when storage is unavailable.
- custom hook
- A function starting with
usethat calls other hooks. It shares stateful logic, not state. - rules of hooks
- Call hooks only at the top level of components and custom hooks, never conditionally, in loops, or after an early return.
- hook slot
- One entry in React's per-component list of hook state, matched to a hook call by its position in call order.
- debounce
- Wait until a value stops changing for a delay before acting on it, for example before searching.
- lazy initial state
- Passing a function to
useState(() => ...)so an expensive initial value (like reading storage) is computed only on the first render. - useSyncExternalStore
- A hook that subscribes a component to a value outside React, with
subscribe,getSnapshot, and an optional server snapshot. - tearing
- Different parts of the UI showing different values of the same external data during one concurrent render.
- hydration mismatch
- When the browser's first render differs from the server HTML, so React discards and re-creates that part of the page.
- renderHook
- A Testing Library helper that runs a hook inside a test component and exposes its latest return value as
result.current.