ReactEasy

What is a custom hook?

A custom hook is a JavaScript function whose name starts with use and that calls other hooks. It extracts reusable stateful logic (fetching, subscriptions, form handling, media queries) out of components. Each component that calls it gets its own independent state.

Rules

  • Name it useSomething, so React and the linter know hook rules apply.
  • Call hooks only at its top level, like in components.
  • It can take arguments and return anything: a value, a tuple, an object, functions.

What it shares and what it does not

  • Shares logic, not state. Two components calling useCounter() each get their own counter.
  • To share state, put it in context or a store and expose it through a hook (useCart() reading a Zustand store).

Good custom hooks

  • Focused on one concern: useOnlineStatus, useDebounce, useLocalStorage, useMediaQuery, useIntersection.
  • Describe the purpose, not the lifecycle: useChatRoom(roomId) rather than useMount.
  • Return stable function references when consumers may use them as dependencies.
  • Clean up their effects.

Before writing one

Check whether a library already solves it well: TanStack Query or SWR for fetching, React Hook Form for forms, usehooks-ts for small utilities. For external stores, build on useSyncExternalStore.

Testing

renderHook from React Testing Library renders a hook in isolation.

Code example

tsx
1import { useEffect, useState } from "react";
2
3export function useMediaQuery(query: string) {
4 const [matches, setMatches] = useState(() => window.matchMedia(query).matches);
5
6 useEffect(() => {
7 const mql = window.matchMedia(query);
8 const onChange = () => setMatches(mql.matches);
9 onChange(); // sync if the query changed
10 mql.addEventListener("change", onChange);
11 return () => mql.removeEventListener("change", onChange);
12 }, [query]);
13
14 return matches;
15}
16
17// Each component gets its own state from the same logic
18export function Nav() {
19 const isMobile = useMediaQuery("(max-width: 640px)");
20 return isMobile ? <button aria-label="Menu">☰</button> : <nav>Home · Docs · Blog</nav>;
21}
22
23export function Hero() {
24 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
25 return <div className={prefersReducedMotion ? "" : "animate-fade-in"}>Welcome</div>;
26}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app