Custom hooks & composition
Extract reusable logic into custom hooks.
By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.
In short
A custom hook is a function starting with use that calls other hooks to package reusable logic. Components share the logic, but each call gets its own independent state.
Explained simply
After a while you notice the same code in many components: listening to the window size, saving a value to localStorage, waiting until the user stops typing. Copying it everywhere means fixing bugs in many places.
A custom hook is a normal function whose name starts with use and which calls other hooks inside. You move the repeated logic into it, and components call it in one line, like const isOnline = useOnlineStatus().
Custom hooks share logic, not state. If two components both call useCounter, each gets its own separate counter. It works exactly as if each component had written the code itself.
Hooks can call other hooks, so you can build bigger ones out of small ones. A useSearch hook might use useDebounce to wait for typing to stop and then fetch results. Each piece stays small and easy to test.
Press Play on a diagram to walk through it one step at a time.
- 1Components
Call useOnlineStatus() and just render the result
- 2Custom hooks
useOnlineStatus, useDebounce, useLocalStorage
- 3Built-in hooks
useState, useEffect, useRef, useContext
- 4Browser APIs
navigator.onLine, localStorage, timers
- useState + useEffect + listener in 3 files
- Bug fixes needed in 3 places
- Components mix UI and plumbing
- Hard to test in isolation
- const online = useOnlineStatus()
- One place to fix and improve
- Components only render
- Hook tested once with renderHook
In depth
Why the rules of hooks exist
React does not see the names of your state variables. It remembers hook state by call order: the first useState call in a component gets slot 1, the second gets slot 2, and so on. On the next render, React hands back the values in the same order.
If a hook is called inside an if, a loop or after an early return, the order can change between renders, and React would give one hook another hook's state. That is why hooks must be called at the top level of a component or custom hook, every render, in the same order. The use prefix lets the eslint-plugin-react-hooks rules find hooks and check this. React 19's use is the one exception that may be called conditionally.
- Step 1Call 1: useState("")
Slot 1 holds the query
- Step 2Call 2: useDebounce()
Its own useState is slot 2
- Step 3Call 3: useEffect()
Slot 3 holds the effect
- Step 4Next render
Same order, same slots, same values
Designing a hook's API
Treat a custom hook like a small library. Name it after its purpose, not its implementation: useOnlineStatus rather than useNavigatorEventListener. Return a single value when there is one result, a tuple when callers will want to rename two things (like useState), and an object when there are three or more fields.
If you return functions that callers may put in effect dependencies or pass to memoized children, keep them stable with useCallback; otherwise every render produces a new function. Accept options as an object with defaults so you can add more later without breaking callers. A hook that calls no hooks is just a function: drop the use prefix.
- One result: return the value
- Two results: return a tuple
- Three or more: return an object
- Stable callbacks with useCallback
- No hooks inside? Then it is not a hook
Subscribing to browser APIs with useSyncExternalStore
Many custom hooks read something outside React that can change: online status, a media query, localStorage, a store. The naive version copies the value into state in an effect. React provides a better primitive: useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot).
subscribe adds a listener and returns an unsubscribe function. getSnapshot returns the current value and must return the same value when nothing changed. getServerSnapshot gives the value to use during server rendering and hydration, where window does not exist. React handles the timing, avoids tearing (different parts of the UI showing different values during one render), and works correctly with concurrent rendering. Keep subscribe stable, defined outside the component or wrapped in useCallback, or React will resubscribe on every render.
Composing hooks
Hooks compose like functions. A component can call useDebounce and pass the result into useSearchResults, and a hook can do the same internally. Each hook owns its own state slots, and values flow from one to the next during the same render.
This keeps every piece small. useDebounce knows nothing about searching. useSearchResults knows nothing about typing speed. useProductSearch combines them for one feature. You can test useDebounce alone with fake timers, and reuse it for an autosave feature later. When a hook grows past one clear job, split it the same way you would split a large component.
- useDebounce(query, 300)
- useState
- useEffect with a timer
- useSearchResults(debounced)
- useState for results and status
- useEffect with AbortController
- returns { results, status }
When not to write a custom hook
Do not extract a hook after seeing logic once. Wait until two or three components truly repeat it; premature hooks hide simple code behind a name you must look up. Avoid lifecycle-style hooks such as useMount or useUpdateEffect: they hide what the effect synchronizes with and make dependency mistakes easy.
Also check whether you need a hook at all. Fetching and caching server data is solved better by TanStack Query, SWR or Next.js server components than by a homemade useFetch. Formatting a date needs a plain function. A good custom hook describes a concrete purpose and wraps real React state or effects.
Learn it in 3 short steps
About 1h each. Track them with a timer in your plan.
- 1Spot repeated logic across components~1h
- 2Extract a custom hook~1h
- 3Compose hooks together~1h
Key points
- Extract a hook when two or more components repeat the same stateful logic.
- Hook names must start with use so React and linters can check the rules.
- Each component calling a hook gets its own separate state.
- Only call hooks at the top level, never inside loops or conditions.
Key terms
Tap a card to flip it. 0/4 known
Examples
import { useEffect, useState } from 'react';
export function useDebounce<T>(value: T, delay = 300): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
// In a component:
// const query = useDebounce(input, 500);A reusable debounce hook built from useState and useEffect.
useMediaQuery with useSyncExternalStore
Step 1: subscribe creates a MediaQueryList and listens for change events; it is wrapped in useCallback so React does not resubscribe every render. Step 2: getSnapshot returns the current matches boolean. Step 3: getServerSnapshot returns false, since the server has no screen; the client corrects it after hydration. Step 4: any component can now write const isWide = useMediaQuery("(min-width: 768px)").
import { useCallback, useSyncExternalStore } from "react";
export function useMediaQuery(query: string): boolean {
const subscribe = useCallback(
(onChange: () => void) => {
const mql = window.matchMedia(query);
mql.addEventListener("change", onChange);
return () => mql.removeEventListener("change", onChange);
},
[query],
);
return useSyncExternalStore(
subscribe,
() => window.matchMedia(query).matches,
() => false,
);
}Composing useDebounce into a search hook
Step 1: reuse useDebounce (from the explainer) to wait 300ms after typing stops. Step 2: fetch only when the debounced query changes, aborting stale requests in cleanup. Step 3: return a small object with results and status. The component stays tiny: const { results, status } = useProductSearch(text).
import { useEffect, useState } from "react";
import { useDebounce } from "./useDebounce";
export function useProductSearch(query: string) {
const debounced = useDebounce(query, 300);
const [results, setResults] = useState<string[]>([]);
const [status, setStatus] = useState<"idle" | "loading" | "error">("idle");
useEffect(() => {
if (!debounced) return;
const ctrl = new AbortController();
setStatus("loading");
fetch(`/api/search?q=${encodeURIComponent(debounced)}`, { signal: ctrl.signal })
.then((r) => r.json()).then((data: string[]) => { setResults(data); setStatus("idle"); })
.catch((e) => { if (e.name !== "AbortError") setStatus("error"); });
return () => ctrl.abort();
}, [debounced]);
return { results, status };
}Quick reference
- A custom hook is a function named useSomething that calls other hooks
- Each call gets its own state; hooks share logic, not data
- Call hooks at the top level, in the same order every render
- Return a value, a tuple or an object depending on how many results there are
- Wrap returned functions in useCallback if callers may use them as dependencies
- Browser or store subscriptions: useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
- Test hooks with renderHook from @testing-library/react
- Server data? Prefer TanStack Query, SWR or server components over a homemade useFetch
Common mistakes
- Calling a hook inside an if statement, which breaks hook order.
- Naming a plain helper useSomething when it calls no hooks.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write useToggle(initial = false) that returns [value, toggle].
- Exercise 2medium
Write useLocalStorage(key, initial) that works like useState but loads the starting value from localStorage and saves every change as JSON.
- Exercise 3hard
Write useOnlineStatus() with useSyncExternalStore, listening to the online and offline window events, returning true on the server.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can custom hooks share state between components?
- No, each call has its own state. To share state, lift it to a common parent, use context, or use an external store that the hook subscribes to.
- Can I call a hook inside a regular function or a loop?
- No. Call hooks only at the top level of components and custom hooks. React 19's use is the only exception that may be called inside conditions and loops.
- How do I test a custom hook?
- Use renderHook from @testing-library/react, read result.current, and wrap updates in act. For timers, use your test runner's fake timers.