الانتقال إلى المحتوى
FrontendReact· 6 دقائق للقراءة

Custom Hooks Share Logic, Not State

Every call to a custom Hook gets its own state. Shared data has to live in one place.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

The team pulls the shopping cart into a tidy useCart() Hook: an array of items, an add function and a count. The product card calls it to add items, and the header badge calls it to show the count. In the demo, someone clicks "Add to cart" three times and the badge keeps saying "Cart (0)". A console.log inside add shows the array growing, so the logic works. It's just growing a different array from the one the badge reads.

The common misconception

The belief: a custom Hook is a small shared service. Put the state in useCart, call useCart() anywhere, and every caller sees the same cart.

It's a reasonable guess. The Hook lives in one module, and a JavaScript module is loaded once, so it feels like whatever is inside gets created once too. The name helps: useCart sounds like "use the cart", not "make yourself a new cart". And some Hooks really do return the same data everywhere: useContext, and the Hooks that state and data-fetching libraries provide, read from something that lives outside your components. Those Hooks share data because of where they read it from, not because they are Hooks.

What actually happens

A custom Hook is part of the component that calls it

A is a plain function whose name starts with use and that calls other Hooks. React keeps no registry of them. When CartBadge calls useCart(), the useState inside runs as if it were written in CartBadge's own body, and its state is stored with CartBadge, at that component's position in the . React's docs put it directly: custom Hooks let you share stateful logic, not state itself, and each call to a Hook is completely independent from every other call to the same Hook.

That holds even inside one component. A form that calls useFormInput("Mary") and useFormInput("Poppins") gets two separate values, just like two useState lines would.

Two callers, two carts

So the cart from the opening has two arrays, one per component. The fix keeps the Hook and moves the state:

TSX cart.tsx
import { useState } from "react";function useCart() {  const [items, setItems] = useState<string[]>([]);  const add = (id: string) => setItems([...items, id]);  return { count: items.length, add };}export function CartBadge() {  const { count } = useCart(); // its own items array, always empty  return <span>Cart ({count})</span>;}export function AddToCart({ productId }: { productId: string }) {  const { add } = useCart(); // a second, unrelated items array  return <button onClick={() => add(productId)}>Add to cart</button>;}

In the first version, a click updates the array of AddToCart, which displays nothing, and re-renders only AddToCart. CartBadge keeps its own empty array and has no reason to render again. In the second, the array exists once, inside CartProvider, and useCart only reads it through context. Wrap the part of the app that holds the header and the products in <CartProvider>, and every caller sees the same cart and re-renders when it changes. Since React 19, the context itself works as the provider: <CartContext value={...}>, no .Provider needed.

Where shared state can live

Sharing means one copy with one owner. React's docs call this a single source of truth, and the usual move is : put the state in the closest common parent and pass it down as props. When that parent is far above, pass it through context, as above. When the data already lives outside React, like the browser's online status or a state library's store, useSyncExternalStore lets every caller subscribe to the same source. In all three cases a custom Hook still earns its place: it hides where the state lives.

What the custom Hook uses insideShared by the components that call it?
useState, useReducerNo: each caller gets its own state
useRefNo: each caller gets its own ref
useEffect that fetches or subscribesNo: each caller runs its own Effect, so three callers send three requests
useContextYes: callers under the same provider read the same value
useSyncExternalStoreYes: callers subscribe to the same external store

The third row surprises people most. A useProducts() Hook that fetches in an Effect, called from the page, the sidebar and the header, sends the same request three times and keeps three copies of the result, which can disagree for a moment. Fetch once in a parent and pass the result down, or use a data library that caches by key.

How to apply it in your project

  1. Find Hooks that hold state several components callSearch for custom Hooks that contain useState or useReducer and are called from more than one component. For each, ask whether those callers are supposed to see the same value.
  2. Pick one owner for state that must be sharedLift it to the closest common parent. If that parent is far up the tree, provide it through context; if it comes from outside React, read it with useSyncExternalStore.
  3. Keep the Hook as the interfaceLet useCart() read the context instead of owning the state, and throw a clear error when it's called outside the provider, so a missing provider fails loudly instead of silently showing an empty cart.
  4. Count the Effects in shared HooksA Hook with a fetch or a subscription runs it once per caller. If three components need the same data, fetch it once above them and pass it down.

Key takeaways

  • A custom Hook reuses code: every call gets its own state, refs and Effects, as if they were written in the caller.
  • Two components calling the same Hook see the same data only when the Hook reads it from one shared place.
  • To share state, lift it to a common parent, provide it through context or subscribe to an external store, and let the Hook hide which one.
  • A module-level variable isn't a fix: React won't re-render when it changes, and on a server every request shares it.

📚 المصادر

  1. Reusing Logic with Custom Hooks — React
  2. Rules of Hooks — React
  3. Sharing State Between Components — React
  4. createContext — React API Reference
  5. useSyncExternalStore — React API Reference

التعليقات (0)