Skip to content

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.

18 min read0/7 questions

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.

ReactuseToggle.tsx
import { useCallback, useState } from "react"; function useToggle(initial = false): [boolean, () => void] { const [on, setOn] = useState(initial); const toggle = useCallback(() => setOn((v) => !v), []); return [on, toggle];} export default function App() { const [isOpen, toggleOpen] = useToggle(); const [isMuted, toggleMuted] = useToggle(true); return ( <div style={{ display: "grid", gap: 8, maxWidth: 260 }}> <button onClick={toggleOpen}>{isOpen ? "Hide" : "Show"} details</button> {isOpen && <p>Shipping takes 3 to 5 days.</p>} <button onClick={toggleMuted}>{isMuted ? "Unmute" : "Mute"}</button> </div> );}

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.

Quick check
Two components both call useOnline(). One of them sets some state inside the hook. Does the other one see that change?
Need a nudge? A hint rules out a wrong answer.

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.

ReactuseOnline.tsx
import { useEffect, useState } from "react"; function useOnline(): boolean { const [isOnline, setIsOnline] = useState(() => navigator.onLine); useEffect(() => { const goOnline = () => setIsOnline(true); const goOffline = () => setIsOnline(false); window.addEventListener("online", goOnline); window.addEventListener("offline", goOffline); return () => { window.removeEventListener("online", goOnline); window.removeEventListener("offline", goOffline); }; }, []); return isOnline;} export default function App() { const isOnline = useOnline(); return ( <p style={{ fontWeight: 600 }}> {isOnline ? "Online: changes sync automatically" : "Offline: changes are saved locally"} </p> );}

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.

ReactuseDebounce.tsx
import { useEffect, useState } from "react"; function useDebounce<T>(value: T, delay: number): T { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); // a new keystroke cancels the old timer }, [value, delay]); return debounced;} export default function App() { const [text, setText] = useState(""); const settled = useDebounce(text, 500); return ( <div> <input type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Type fast..." /> <p>Live: {text}</p> <p>Debounced (500 ms): {settled}</p> </div> );}

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:

  1. Only call hooks at the top level of a component or custom hook. Never inside conditions, loops, nested functions, or after an early return.
  2. 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.

How React matches hooks to slots
  1. Slot 1: useState("Ada")name
  2. Slot 2: useState(36)age
  3. Slot 3: useEffect(...)sync title
  4. Slot 4: useDebounce → useState + useEffectcustom hooks add their slots inline

Render 1: the first useState call creates slot 1 and stores "Ada".

1/5
Quick check
Which line breaks the rules of hooks?
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} />;
}
Need a nudge? A hint rules out a wrong answer.
Predict the outputJavaScript

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} />;
}
Need a nudge? Hints walk you through it.

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, like formatPrice, should stay a normal function so it can be called anywhere, including in conditions.
  • Name it after the purpose, not the mechanics. useChatRoom(roomId) beats useWebSocketEffect. When a component reads const 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.
Put it in order4 steps

You notice two components with the same online-status logic. Put the refactor in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 useState and dispatch from useReducer are 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).
ReactStableActions.tsx
import { memo, useMemo, useState } from "react"; function useCounter(initial = 0) { const [count, setCount] = useState(initial); // Built once: the functions only use the updater form, so they never go stale. const actions = useMemo(() => ({ increment: () => setCount((c) => c + 1), reset: () => setCount(initial), }), [initial]); return [count, actions] as const;} type Actions = ReturnType<typeof useCounter>[1]; const Controls = memo(function Controls({ actions }: { actions: Actions }) { console.log("Controls rendered"); return ( <div style={{ display: "flex", gap: 8 }}> <button onClick={actions.increment}>Add one</button> <button onClick={actions.reset}>Reset</button> </div> );}); export default function App() { const [count, actions] = useCounter(); return ( <div> <p>Count: {count}</p> <Controls actions={actions} /> </div> );}

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.

Quick check
A 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?
Need a nudge? A hint rules out a wrong answer.

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 calls callback whenever 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 by Object.is.
  • getServerSnapshot() returns the value to use during server rendering and hydration.
ReactuseSyncExternalStore.tsx
import { useSyncExternalStore } from "react"; // Defined outside the component, so React sees the same function every render.function subscribeOnline(callback: () => void) { window.addEventListener("online", callback); window.addEventListener("offline", callback); return () => { window.removeEventListener("online", callback); window.removeEventListener("offline", callback); };} function useOnline() { return useSyncExternalStore(subscribeOnline, () => navigator.onLine, () => true);} function useMediaQuery(query: string) { return useSyncExternalStore( (callback) => { const list = window.matchMedia(query); list.addEventListener("change", callback); return () => list.removeEventListener("change", callback); }, () => window.matchMedia(query).matches, () => false, // the server has no screen: pick a safe default );} export default function App() { const isOnline = useOnline(); const isNarrow = useMediaQuery("(max-width: 500px)"); const prefersDark = useMediaQuery("(prefers-color-scheme: dark)"); return ( <ul> <li>Network: {isOnline ? "online" : "offline"}</li> <li>Layout: {isNarrow ? "narrow (under 500px)" : "wide"}</li> <li>System theme: {prefersDark ? "dark" : "light"}</li> </ul> );}

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:

  1. getSnapshot must 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.
  2. subscribe should be stable. An inline function, as in useMediaQuery above, 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 in useCallback keyed on its inputs (query here).
Quick check
A hook calls useSyncExternalStore(subscribe, () => ({ x: window.scrollX, y: window.scrollY })). The page crashes on first render. Why?
Need a nudge? A hint rules out a wrong answer.

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.

components/ClientOnlyMap.tsx
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.

useDebounce.test.ts
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.current is 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 uses await act(async () => ...) or waitFor.
  • A hook that needs a provider takes a wrapper option: 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 it in order5 steps

Put the steps of a useDebounce test with fake timers in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

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-insensitive includes).
  • 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 matches instead of the list items.
FRUITS = Apple, Apricot, Banana, Cherry, Grape, Mango
"ap" → Apple, Apricot, Grape
React
import { useEffect, useState } from "react"; const FRUITS = ["Apple", "Apricot", "Banana", "Cherry", "Grape", "Mango"]; function useDebounce<T>(value: T, delay: number): T { // Keep a debounced copy in state and update it with a timer in an effect. return value;} export default function App() { const [query, setQuery] = useState(""); return ( <div> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} /> <ul> {FRUITS.map((fruit) => ( <li key={fruit}>{fruit}</li> ))} </ul> </div> );}
ChallengeMedium

A 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 light and dark.

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.

React
import { useEffect, useState } from "react"; function useLocalStorage<T>( key: string, initialValue: T,): [T, (value: T) => void] { // Read the saved value once (lazily), keep it in state, and write it back when it changes. return [initialValue, () => {}];} export default function App() { const [theme, setTheme] = useLocalStorage("theme", "light"); return ( <div> <p>Theme: {theme}</p> <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}> Toggle theme </button> </div> );}
Key terms
custom hook
A function starting with use that 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.