Cart Context Demo

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

Provider CartContext createContext() App mounts the provider CartProvider owns state, provides value Header passes through Main passes through CartBadge reads count ProductList passes through CartSummary reads count, clears it Product adds one Product adds one Product adds one
  • 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

ComponentRoleWhat it does with the contextRe-renders on click
CartContextCreatescreateContext() at module level. Holds nothing itself; it is the channel the other components use.Not a component
AppMountsRenders CartProvider around the two branches. Does not touch the context.No
CartProviderProvidesHolds count in useState(0) and passes { count, setCount } to CartContext.Provider.Yes, its own state changed
HeaderPasses throughOnly lays out its child. No props about the cart.No
CartBadgeConsumesuseContext, then reads count to show the number.Yes
MainPasses throughOnly lays out ProductList and CartSummary.No
ProductListPasses throughOnly lays out the three products.No
Product ×3ConsumesuseContext, then calls setCount(c => c + 1). It never reads count.Yes, the context value is a new object each time
CartSummaryConsumesuseContext, reads count to show it and calls setCount(0) on Clear.Yes