
Custom Hooks Share Logic, Not State
- كاتب موثّق
- React 19
محتويات المقال
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
useCart, call useCart() anywhere, and every caller sees the same cart.
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
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.
useFormInput("Mary") and useFormInput("Poppins") gets two separate values, just like two useState lines would.
Two callers, two carts
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>;}import { createContext, useContext, useState, type ReactNode } from "react";type Cart = { count: number; add: (id: string) => void };const CartContext = createContext<Cart | null>(null);export function CartProvider({ children }: { children: ReactNode }) { // The only items array, owned by a parent of every cart component const [items, setItems] = useState<string[]>([]); const add = (id: string) => setItems([...items, id]); return ( <CartContext value={{ count: items.length, add }}>{children}</CartContext> );}// Same name, same return shape: CartBadge and AddToCart don't changeexport function useCart(): Cart { const cart = useContext(CartContext); if (!cart) throw new Error("useCart must be used inside <CartProvider>"); return cart;}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
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.
useState, useReducer | |
useRef | |
useEffect that fetches or subscribes | |
useContext | |
useSyncExternalStore |
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
Find Hooks that hold state several components call Search for custom Hooks that contain useStateoruseReducerand are called from more than one component. For each, ask whether those callers are supposed to see the same value.Pick one owner for state that must be shared Lift 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.Keep the Hook as the interface Let 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.Count the Effects in shared Hooks A 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.
التعليقات (0)