ReactMedium

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

  1. Find repeated logic: the same useState + useEffect pattern in several components.
  2. Move it into function useX(params) { ... }.
  3. Return a clear API: a value, a tuple, or an object with values and actions.
  4. 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 expose useCart().
  • 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

tsx
1import { useSyncExternalStore } from "react";
2
3// 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>();
7
8export 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};
19
20// The hook exposes the shared state to any component
21export function useCart() {
22 return useSyncExternalStore(cartStore.subscribe, cartStore.getSnapshot, () => items);
23}
24
25export function CartBadge() {
26 const cart = useCart();
27 return <span>🛒 {cart.length}</span>;
28}
29
30export 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.

Open in study app