Sub topic 8
Extracting logic into custom hooks
A custom hook is a function whose name starts with use and that calls other hooks. This chapter assumes you know useState, useEffect, and props, and that you have read the earlier chapters on feature modules and component layers. Here you will learn when to pull logic out of a component, where the hook file belongs, and which mistakes to avoid.
Why hooks matter for structure
Components in a large codebase tend to grow two jobs: deciding what to show, and deciding how data behaves. When both live in one function, the file gets long, tests need a full render, and the same logic gets copied into the next component.
A custom hook gives the second job its own home. The component keeps the markup. The hook keeps state, effects, and derived values. Hooks share logic, not state. Each component that calls a hook gets its own copy of that hook's state.
Where hooks live
In a feature module, hooks go in the feature's hooks/ folder. Anything the rest of the app needs is re-exported from the feature's index.ts. Hooks used by several features go in shared/.
src/
features/
cart/
components/
CartList.tsx
hooks/
useCart.ts
useCart.test.ts
index.ts
shared/
hooks/
useDebouncedValue.tsUse this rule of thumb to choose between the two locations:
| Hook | Location | Reason |
|---|---|---|
| `useCart` | `features/cart/hooks` | Knows about cart items and cart rules |
| `useOrders` | `features/orders/hooks` | Wraps the orders API |
| `useDebouncedValue` | `shared/hooks` | Knows nothing about any feature |
A shared hook must not import from a feature. If it needs to, it belongs in that feature.
When to extract a hook
Extract when one of these is true:
- The same state and effect logic appears in two or more components.
- A component has several pieces of state that change together.
- An effect sets up and tears down something (a listener, a timer, a subscription) and you want to test it alone.
- The component body is hard to read because logic buries the markup.
Do not extract just to make a file shorter. A hook used in exactly one place, with one useState and no effect, often adds an extra file to open without making anything clearer.
A worked example
Here is a component that mixes logic and markup. It tracks cart items and computes a total.
import { useState } from "react";
type CartItem = { id: string; name: string; price: number; qty: number };
export function CartList({ initial }: { initial: CartItem[] }) {
const [items, setItems] = useState(initial);
const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
function remove(id: string) {
setItems((current) => current.filter((i) => i.id !== id));
}
return (
<div>
<ul>
{items.map((i) => (
<li key={i.id}>
{i.name} x {i.qty}
<button onClick={() => remove(i.id)}>Remove</button>
</li>
))}
</ul>
<p>Total: {total}</p>
</div>
);
}Move the state and rules into useCart:
// src/features/cart/hooks/useCart.ts
import { useCallback, useMemo, useState } from "react";
import type { CartItem } from "../types";
export function useCart(initial: CartItem[] = []) {
const [items, setItems] = useState<CartItem[]>(initial);
const total = useMemo(
() => items.reduce((sum, i) => sum + i.price * i.qty, 0),
[items]
);
const remove = useCallback((id: string) => {
setItems((current) => current.filter((i) => i.id !== id));
}, []);
return { items, total, remove };
}The component now only describes the UI:
// src/features/cart/components/CartList.tsx
import { useCart } from "../hooks/useCart";
import type { CartItem } from "../types";
export function CartList({ initial }: { initial: CartItem[] }) {
const { items, total, remove } = useCart(initial);
return (
<div>
<ul>
{items.map((i) => (
<li key={i.id}>
{i.name} x {i.qty}
<button onClick={() => remove(i.id)}>Remove</button>
</li>
))}
</ul>
<p>Total: {total}</p>
</div>
);
}The hook's return value is its public surface. Return only what callers need, and name the fields for what they mean. Here items, total, and remove say nothing about how the state is stored, so you can later switch from useState to a reducer without touching CartList.
Hooks and the data layer
A hook is also the right place to connect components to the data access layer. The earlier api.ts file does the fetch. The hook wraps it with a server-state library, so components never call fetch directly.
// src/features/orders/hooks/useOrders.ts
import { useQuery } from "@tanstack/react-query";
import { fetchOrders } from "../api";
export function useOrders(userId: string) {
return useQuery({
queryKey: ["orders", userId],
queryFn: () => fetchOrders(userId),
});
}Every component that calls useOrders("42") shares one cached result, because the query key is the same. This is the one place where hook callers appear to share state. The sharing comes from the cache, not from the hook.
Rules and common errors
Custom hooks follow the same rules as built-in hooks. Most bugs come from breaking one of them.
Calling a hook conditionally
Hooks must run in the same order on every render. Do not call them inside if, loops, or after an early return.
function Profile({ id }: { id: string | null }) {
if (!id) return null; // early return before the hook below
const { data } = useOrders(id); // breaks the rules of hooks
return <p>{data?.length}</p>;
}The ESLint plugin eslint-plugin-react-hooks reports this. Keep it enabled. To skip work when id is missing, pass an option such as enabled to the query inside the hook instead of skipping the call.
Stale values from missing dependencies
A hook that reads a prop or state inside useEffect, useMemo, or useCallback must list it in the dependency array. Leaving it out gives you a function that sees old values.
import { useEffect, useState } from "react";
export function useDocumentTitle(title: string) {
useEffect(() => {
document.title = title;
}, [title]); // omit this and the title never updates
}
export function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return width;
}useWindowWidth shows the cleanup pattern. Whatever the effect starts, the returned function stops. Without it, every mount adds another listener and none are removed.
Unstable return values
If a hook returns a new object or function on every render, any child that receives it as a prop or effect dependency will re-run each time. Wrap returned functions in useCallback and derived objects in useMemo when callers depend on them. Do this where it matters, not everywhere. Wrapping every value adds noise and costs memory.
Hooks that do too much
A hook called useCheckoutPage that fetches orders, tracks form fields, and manages a modal is a component in disguise. Split it into smaller hooks and compose them:
export function useCheckout(userId: string) {
const orders = useOrders(userId);
const cart = useCart();
return { orders, cart };
}A hook should have one reason to change. If you struggle to name it without the word "and", split it.
Treating a hook as global state
Calling useCart() in two components creates two separate carts. If both must see the same cart, the state has to live above them (in a parent, a context, or a store) or in a server cache. The chapter on deciding where state lives covers that choice. Moving logic into a hook does not move the state any higher in the tree.
Testing hooks
Because hooks hold logic apart from markup, you can test them directly with renderHook from React Testing Library.
// src/features/cart/hooks/useCart.test.ts
import { act, renderHook } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { useCart } from "./useCart";
describe("useCart", () => {
it("removes an item and updates the total", () => {
const { result } = renderHook(() =>
useCart([
{ id: "a", name: "Pen", price: 2, qty: 3 },
{ id: "b", name: "Pad", price: 5, qty: 1 },
])
);
expect(result.current.total).toBe(11);
act(() => result.current.remove("a"));
expect(result.current.items).toHaveLength(1);
expect(result.current.total).toBe(5);
});
});The test file sits next to the hook, following the colocation rule from the naming chapter. Test the hook's behavior through its return value. Leave the component test for what the user sees.
Exposing hooks through the public API
Other features should import useCart from the feature's index file, not from hooks/useCart:
// src/features/cart/index.ts
export { CartList } from "./components/CartList";
export { useCart } from "./hooks/useCart";
export type { CartItem } from "./types";Export a hook only if another feature really needs it. Hooks that support one internal component stay private. A smaller public API means fewer places break when you refactor.
Summary of decisions
- Start with logic in the component. Extract when you see duplication, tangled state, or an effect worth testing alone.
- Place the hook in the feature's
hooks/folder. Move it toshared/hooksonly if it has no feature knowledge. - Return a small, well-named object. Hide how the state is held.
- Wrap
api.tscalls with a server-state hook rather than callingfetchin components. - Keep hooks private unless another feature needs them, and export them through
index.tswhen it does.
Exercise
Two sibling components both call useCart(). A user removes an item in one, but the other still shows it. Why does this happen, and what are two ways to fix it?
Show answer
Each call to a hook creates its own state, so the two components hold separate carts. Hooks share logic, not state. Fix it by lifting the state to a common parent or a context provider that calls useCart() once and passes the result down, or by moving the cart into a shared store or server-state cache that both components read from.
Exercise
A component contains if (!userId) return null; followed by const { data } = useOrders(userId);. What rule does this break, and how do you rewrite it?
Show answer
It breaks the rule that hooks must be called in the same order on every render, because the early return skips the hook on some renders. Call the hook first and let it skip the work, for example by adding enabled: Boolean(userId) to the query options inside the hook, then return null after the hook call if there is no data to show.