Skip to content

perf: Stabilize Cart context function references with useCallback/useMemo #15

@yortch

Description

@yortch

User Story

As a shopper browsing products,
I want the product listing and navigation to remain responsive when I add or modify items in my cart,
so that interacting with the cart doesn't cause unnecessary page slowdowns.

Problem

All functions in CartContext (addToCart, removeFromCart, updateQuantity, clearCart, getTotalItems, getTotalPrice) are recreated on every render and passed directly through context. Every component that consumes CartContext will re-render on any state change, even if the component doesn't depend on the changed value.

// Current — new function references on every render
const addToCart = (product, quantity) => { ... };
const removeFromCart = (productId) => { ... };
// etc.

Acceptance Criteria

  • addToCart, removeFromCart, updateQuantity, clearCart are wrapped with useCallback with correct dependency arrays
  • getTotalItems and getTotalPrice are replaced with memoized values using useMemo
  • Components consuming cart context do not re-render unnecessarily when unrelated cart state changes
  • All existing cart functionality (add, remove, update quantity, clear, totals) continues to work correctly
  • No change to visible behavior for the user

Files

  • frontend/src/context/CartContext.tsx

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions