
Context Is Not a State Manager: How Context Updates Re-render Consumers
- كاتب موثّق
- React 19
محتويات المقال
useContext(CartContext) to get dispatch, and that same context also carries the items.
The common misconception
useContext, and React re-renders only the components that read the part of the value that changed, the way a store with selectors would.
const { dispatch } = useContext(CartContext) even looks like a subscription to one field. It isn't.
What actually happens
Context delivers a value; it doesn't manage it
useState or useReducer inside the provider component, and updating it is ordinary React state: the provider re-renders and passes down a new value. Context adds no update API, no selectors and no middleware. In React's own pattern, the reducer manages the state and context delivers it.
Every reader gets the whole value
Object.is, React re-renders every component that reads that context, starting from the provider, and memo doesn't stop it. React doesn't track which fields a component uses. Destructuring dispatch happens after the read, so a button that only needs dispatch is subscribed to the items too.
useMemo fixes that, and the useContext docs recommend it. But memoization can't help when the data inside really changed: a memoized { items, dispatch } is still a new object every time an item is added, so every reader renders.
Split the value along how it changes
dispatch. The useReducer docs say dispatch has a stable identity, so a context that holds only dispatch never gets a new value, and components that only send actions never re-render because of it:
import { createContext, useContext, useMemo, useReducer } from "react";import type { ReactNode } from "react";const CartContext = createContext<CartValue | null>(null);export function CartProvider({ children }: { children: ReactNode }) { const [items, dispatch] = useReducer(cartReducer, []); // Memoized, yet a new object every time items change const value = useMemo(() => ({ items, dispatch }), [items]); return <CartContext value={value}>{children}</CartContext>;}export function AddToCartButton({ id }: { id: string }) { const { dispatch } = useContext(CartContext)!; // renders on every add return ( <button onClick={() => dispatch({ type: "add", id })}>Add to cart</button> );}import { createContext, useContext, useReducer } from "react";import type { ReactNode } from "react";const CartContext = createContext<CartItem[]>([]);const CartDispatchContext = createContext<CartDispatch>(() => {});export function CartProvider({ children }: { children: ReactNode }) { const [items, dispatch] = useReducer(cartReducer, []); return ( <CartContext value={items}> <CartDispatchContext value={dispatch}>{children}</CartDispatchContext> </CartContext> );}export function AddToCartButton({ id }: { id: string }) { const dispatch = useContext(CartDispatchContext); // never changes return ( <button onClick={() => dispatch({ type: "add", id })}>Add to cart</button> );}CartContext, so only its readers, like the header count, render. The 48 buttons read CartDispatchContext, whose value is the same function every time, and they stay still. One condition: the product grid must reach the provider as children, so the provider's own re-render doesn't drag it along.
When you need a real store
useSyncExternalStore: when the store changes, it re-renders the component only if the snapshot it returns differs under Object.is. Store libraries offer hooks built on the same idea. React Redux's docs say useSelector compares the selected result with === after each action and re-renders only when it changed, so a selector that builds a new object every time re-renders every time.
useState or useReducer in the provider | ||
How to apply it in your project
Profile one update Record a single interaction in the React DevTools Profiler. Look for context readers that rendered but show nothing that changed. Map each context's fields For each context, write down what's in its value, how often each part changes, and which components read which part. Split by rate of change Separate state from dispatch, and fast-changing values from stable ones. Memoize any object value that remains.Move busy, sliced data to a store When splits multiply and many components each read a small part of frequently changing data, use a store with selectors.
Key takeaways
Context delivers one value to a subtree; the state behind it is ordinary useStateoruseReducerin the provider.When that value changes, every reader re-renders, whatever fields it uses, and memodoesn't stop it.useMemostops new values on unrelated renders, but not when the data inside really changed.Narrow updates by splitting contexts, state from dispatch; for many readers of busy data, use a store with selectors.
التعليقات (0)