Cart Context Demo
One piece of state, held by CartProvider, read by components in two separate branches. Click Add to cart and watch which boxes light up.
Provider owns the state
Flashes when the component re-renders
renders n counts how often each one has rendered
Component tree
-
Approot, renders once
-
CartProviderowns the state
-
Headerno context
- CartBadgereads count
-
Mainno context
-
ProductListno context
- Product ×3calls setCount
- CartSummaryreads count, calls setCount
-
-
-
Green outline: calls useContext. Grey outline: does not. Nodes flash here too when that component re-renders.
Tree diagram
- Provides: owns the state and puts it in context
- Consumes: reads
count - Consumes: calls
setCount - Re-renders when the count changes
- Created once at module level, not a component
Boxes turn green for a moment when that component re-renders.
Who does what
| Component | Role | What it does with the context | Re-renders on click |
|---|---|---|---|
| CartContext | Creates | createContext() at module level. Holds nothing itself; it is the channel the other components use. | Not a component |
| App | Mounts | Renders CartProvider around the two branches. Does not touch the context. | No |
| CartProvider | Provides | Holds count in useState(0) and passes { count, setCount } to CartContext.Provider. | Yes, its own state changed |
| Header | Passes through | Only lays out its child. No props about the cart. | No |
| CartBadge | Consumes | useContext, then reads count to show the number. | Yes |
| Main | Passes through | Only lays out ProductList and CartSummary. | No |
| ProductList | Passes through | Only lays out the three products. | No |
| Product ×3 | Consumes | useContext, then calls setCount(c => c + 1). It never reads count. | Yes, the context value is a new object each time |
| CartSummary | Consumes | useContext, reads count to show it and calls setCount(0) on Clear. | Yes |
- Siblings share state without props.
Productin one branch updatesCartBadgein the other. - Header, Main and ProductList never re-render. They don't call
useContext, and their children are unchanged elements. - Every consumer re-renders on any change.
Productonly usessetCount, yet its counter still goes up, because the context value is a new object each time.