How to share logic via hooks?
Extract the stateful logic into a custom hook (useSomething) that calls built-in hooks and returns what components need. Every component that calls it gets its own copy of the state with the same behavior. To share the same state, put it in context or an external store and expose it through a hook.
Steps
- Find repeated logic: the same
useState+useEffectpattern in several components. - Move it into
function useX(params) { ... }. - Return a clear API: a value, a tuple, or an object with values and actions.
- Replace the duplicated code with
const x = useX(...).
Sharing logic vs sharing state
- Logic:
useOnlineStatus()in two components subscribes twice and gives each its own state, which is fine because both read the same browser value. - State: a shopping cart must be the same everywhere. Use context +
useReducer, or a store like Zustand, and exposeuseCart(). - External sources: build on
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)for browser APIs or custom stores; it is concurrency-safe and supports SSR.
Composition
Custom hooks can call other custom hooks: useSearch uses useDebounce and useQuery.
Compared to older patterns
Higher-order components and render props also share logic but add wrapper layers and prop collisions. Hooks share logic without changing the component tree.
Testing
Use renderHook from React Testing Library, and test the store or reducer separately.
Code example
1import { useSyncExternalStore } from "react";23// One external store shared by every component (state is shared, not copied)4type CartItem = { id: string; name: string };5let items: CartItem[] = [];6const listeners = new Set<() => void>();78export const cartStore = {9 add(item: CartItem) {10 items = [...items, item];11 listeners.forEach((l) => l());12 },13 subscribe(listener: () => void) {14 listeners.add(listener);15 return () => listeners.delete(listener);16 },17 getSnapshot: () => items,18};1920// The hook exposes the shared state to any component21export function useCart() {22 return useSyncExternalStore(cartStore.subscribe, cartStore.getSnapshot, () => items);23}2425export function CartBadge() {26 const cart = useCart();27 return <span>🛒 {cart.length}</span>;28}2930export function AddButton() {31 return <button onClick={() => cartStore.add({ id: crypto.randomUUID(), name: "Pen" })}>Add</button>;32}
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.