Sub topic 8
Extracting logic into custom hooks
This chapter assumes you know React components, props, and the built-in hooks (useState, useMemo, useEffect). It also assumes you have read the earlier chapters on feature modules and component layers.
What a custom hook is
A custom hook is a function whose name starts with use and that calls other hooks. It moves stateful logic out of a component so the component can focus on markup. Each component that calls the hook gets its own copy of the state. A hook shares logic, not data.
When to extract
Extract when a component mixes rendering with logic that has its own name, such as "cart totals" or "load orders for a user". Extract when two components need the same logic. Extract when you want to test the logic without rendering anything. Do not extract a single useState call just to have a hook.
Worked example
This component keeps its state and calculations inline.
// src/features/cart/components/CartList.tsx (before)
import { useState } from "react";
export type CartItem = { id: string; name: string; price: number; quantity: number };
export function CartList({ initial }: { initial: CartItem[] }) {
const [items, setItems] = useState(initial);
const total = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
function remove(id: string) {
setItems((current) => current.filter((i) => i.id !== id));
}
return (
<section>
<ul>
{items.map((i) => (
<li key={i.id}>
{i.name} x{i.quantity}
<button onClick={() => remove(i.id)}>Remove</button>
</li>
))}
</ul>
<p>Total: {total}</p>
</section>
);
}Move the state and the total into a hook in the feature's hooks folder.
// src/features/cart/hooks/useCart.ts
import { useCallback, useMemo, useState } from "react";
export type CartItem = { id: string; name: string; price: number; quantity: number };
export function useCart(initial: CartItem[]) {
const [items, setItems] = useState(initial);
const total = useMemo(
() => items.reduce((sum, i) => sum + i.price * i.quantity, 0),
[items],
);
const remove = useCallback((id: string) => {
setItems((current) => current.filter((i) => i.id !== id));
}, []);
return { items, total, remove };
}// src/features/cart/components/CartList.tsx (after)
import { useCart, type CartItem } from "../hooks/useCart";
export function CartList({ initial }: { initial: CartItem[] }) {
const { items, total, remove } = useCart(initial);
return (
<section>
<ul>
{items.map((i) => (
<li key={i.id}>
{i.name} x{i.quantity}
<button onClick={() => remove(i.id)}>Remove</button>
</li>
))}
</ul>
<p>Total: {total}</p>
</section>
);
}The component now only describes what to show. The hook owns what the data is and how it changes.
Where hooks sit in the layers
A hook belongs to the feature that owns its concern. It may call that feature's api.ts file, as useOrders does. Components call hooks, and hooks call the data access layer.
Export a hook from the feature's index.ts only when other features need it. Hooks with no feature-specific knowledge, such as useDebounce, go in shared/lib.
Common errors
- Expecting shared state. Two components calling
useCarteach get separate state. To share state, lift it into a context, a store, or a server-state cache. - One giant hook. A hook that returns fifteen values is a component in disguise. Split it by concern.
- Unstable return values. Returning a new object or function on each render can retrigger effects in callers. Wrap functions in
useCallbackand derived values inuseMemowhen callers depend on them. - Rendering inside hooks. A hook returns data and functions. Keep JSX in components.
- Conditional calls. Hooks must run in the same order on every render. Never call them inside
ifblocks or loops.
Exercise
Two sibling components both call useCart(initialItems). One removes an item, but the other still shows it. Why, and what is one way to fix it?
Show answer
Each call to a custom hook creates its own state, so the two components hold separate copies. To fix it, move the cart state to a shared place, such as a context provider or a store that both components read, and have useCart read from it.