Skip to content
Twilight React Playground
ثيم رائدaren

CartContextProvider

providerAdvancedserverbrowser

A React context for a cart object: wrap part of the page once, then read the cart anywhere inside it with useCartContext().

import { CartContextProvider, useCartContext, CartContext, CartContextValue, CartContextProviderProps } from '@salla.sa/twilight-theme-engine/contexts';

In plain words

The same idea as the product context, for a cart: <CartContextProvider value={{ cart }}> around part of the page, then useCartContext() inside returns { cart }, or null outside a provider.

You supply the cart. The context does not fetch it or keep it up to date.

Signature

interface CartContextValue {
  cart: Cart;
}

interface CartContextProviderProps {
  children: ReactNode;
  value: CartContextValue;
}

function CartContextProvider(props: CartContextProviderProps): React.ReactElement
function useCartContext(): CartContextValue | null
const CartContext: React.Context<CartContextValue | null>

Example

app/components/CartSummary.tsx
import { CartContextProvider, useCartContext } from '@salla.sa/twilight-theme-engine/contexts';
import type { Cart } from '@salla.sa/twilight-theme-engine/types';

function ItemCount() {
  const context = useCartContext();
  return <span>{context?.cart.count ?? 0} items</span>;
}

export function CartSummary({ cart }: { cart: Cart }) {
  return (
    <CartContextProvider value={{ cart }}>
      <ItemCount />
    </CartContextProvider>
  );
}

How it behaves

  • A plain React context that nothing in the engine reads. It memoizes its value on value.cart: pass a new cart object when the cart changes, or consumers keep the old one.

  • CartContext itself is exported for use(CartContext) and class components.

Gotchas

  • Like the product context, its source comment says HookSlot injects it into cart:* handlers; it does not. Pass context={{ cart }} to the slot.

Related

Source and docs