Use Cart
Shopping cart React hook for ecommerce: a client hook for cart state with lines, quantity clamping, remove, clear and reset, plus totals with pluggable shipping and tax estimates. Exports helpers for minor-unit money formatting.
"use client"
import { useCallback, useMemo, useState } from "react"
// A line is one product variant in the cart. Its id is the line's own, never
// the product's: two variants of one product are two lines.
type CartLine = {
id: string
productId: string
name: string
href: string
options: readonly string[]
unitPrice: number
quantity: number
maxQuantity?: number
imageUrl: string
imageAlt: string
inStock: boolean
leadTime?: string
}
// Estimates are the knob: each takes the subtotal in minor units and returns
// minor units. Nothing here knows a real tax rule or carrier.
type CartEstimate = {
shipping?: (subtotal: number, lines: readonly CartLine[]) => number
tax?: (subtotal: number, lines: readonly CartLine[]) => number
}
type CartTotals = {
count: number
subtotal: number
shipping: number
tax: number
total: number
}
const DEFAULT_MAX_QUANTITY = 8
function cartCount(lines: readonly CartLine[]) {
return lines.reduce((sum, line) => sum + line.quantity, 0)
}
function cartLineAmount(line: Pick<CartLine, "unitPrice" | "quantity">) {
return line.unitPrice * line.quantity
}
function cartTotals(
lines: readonly CartLine[],
estimate: CartEstimate = {}
): CartTotals {
const subtotal = lines.reduce((sum, line) => sum + cartLineAmount(line), 0)
const shipping = lines.length
? (estimate.shipping?.(subtotal, lines) ?? 0)
: 0
const tax = lines.length ? (estimate.tax?.(subtotal, lines) ?? 0) : 0
return {
count: cartCount(lines),
subtotal,
shipping,
tax,
total: subtotal + shipping + tax,
}
}
function cartLineLabel(line: Pick<CartLine, "name" | "options">) {
return [line.name, ...line.options].join(", ")
}
function clampQuantity(line: CartLine, quantity: number) {
const max = line.maxQuantity ?? DEFAULT_MAX_QUANTITY
if (!Number.isInteger(quantity)) return line.quantity
return Math.min(Math.max(quantity, 1), max)
}
const formatters = new Map<string, Intl.NumberFormat>()
// Amounts are integer minor units; the currency decides how many make a unit.
function formatMoney(
amount: number,
{ currency = "USD", locale = "en-US" } = {}
) {
const key = `${locale}:${currency}`
let formatter = formatters.get(key)
if (!formatter) {
formatter = new Intl.NumberFormat(locale, { style: "currency", currency })
formatters.set(key, formatter)
}
const digits = formatter.resolvedOptions().maximumFractionDigits ?? 2
return formatter.format(amount / 10 ** digits)
}
function useCart<Line extends CartLine>(
initialLines: readonly Line[],
estimate?: CartEstimate
) {
const [lines, setLines] = useState<readonly Line[]>(initialLines)
const setQuantity = useCallback((id: string, quantity: number) => {
setLines((current) =>
current.map((line) =>
line.id === id
? { ...line, quantity: clampQuantity(line, quantity) }
: line
)
)
}, [])
const remove = useCallback((id: string) => {
setLines((current) => current.filter((line) => line.id !== id))
}, [])
const clear = useCallback(() => setLines([]), [])
const reset = useCallback(() => setLines(initialLines), [initialLines])
const totals = useMemo(() => cartTotals(lines, estimate), [lines, estimate])
return {
lines,
totals,
count: totals.count,
isEmpty: lines.length === 0,
setQuantity,
remove,
clear,
reset,
}
}
export {
useCart,
cartTotals,
cartCount,
cartLineAmount,
cartLineLabel,
formatMoney,
DEFAULT_MAX_QUANTITY,
type CartLine,
type CartEstimate,
type CartTotals,
}
"use client"
import { useEffect, useRef, useState } from "react"
import { MinusIcon, PlusIcon } from "@phosphor-icons/react"
import {
cartLineAmount,
cartLineLabel,
DEFAULT_MAX_QUANTITY,
formatMoney,
useCart,
type CartEstimate,
type CartLine,
} from "@/hooks/use-cart"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
// The copy: change text here, not in the markup.
const COPY = {
title: "Your bag",
decrease: "Decrease quantity of",
increase: "Increase quantity of",
remove: "Remove",
removed: "removed",
quantityOf: (name: string, quantity: number) =>
`${name}, quantity ${quantity}`,
subtotal: "Subtotal",
shipping: "Shipping",
freeShipping: "Free",
tax: "Tax",
total: "Total",
empty: "Your bag is empty.",
reset: "Put the prints back",
} as const
// Each line's swatch: the print's two main colors.
const SWATCHES: Record<string, readonly [string, string]> = {
fern: ["oklch(0.62 0.08 150)", "oklch(0.2 0.02 150)"],
"copper-column": ["oklch(0.62 0.15 55)", "oklch(0.18 0.01 55)"],
vesper: ["oklch(0.55 0.12 300)", "oklch(0.25 0.06 280)"],
}
const LINES: CartLine[] = [
{
id: "line-fern-rag",
productId: "fern",
name: "Fern",
href: "#",
options: ["Cotton rag"],
unitPrice: 13500,
quantity: 1,
imageUrl: "",
imageAlt: "",
inStock: true,
},
{
id: "line-copper-column-washi",
productId: "copper-column",
name: "Copper Column",
href: "#",
options: ["Washi"],
unitPrice: 12500,
quantity: 2,
imageUrl: "",
imageAlt: "",
inStock: true,
},
{
id: "line-vesper-rag",
productId: "vesper",
name: "Vesper",
href: "#",
options: ["Cotton rag"],
unitPrice: 9500,
quantity: 1,
imageUrl: "",
imageAlt: "",
inStock: true,
},
]
// Sample estimates in cents: shipping is free from $400, tax is 8.25%.
const ESTIMATE: CartEstimate = {
shipping: (subtotal) => (subtotal >= 40000 ? 0 : 1200),
tax: (subtotal) => Math.round(subtotal * 0.0825),
}
/** A bag of prints on useCart: steppers change each line, remove drops it,
* and the subtotal, shipping, tax and total follow from the hook. */
export default function UseCartDemo() {
const { lines, totals, isEmpty, setQuantity, remove, reset } = useCart(
LINES,
ESTIMATE
)
// One status line outlives the rows, so a removal is still announced.
const [announcement, setAnnouncement] = useState("")
// Where focus goes once a removed row is gone: the next line's Remove, or
// the empty bag's button.
const content = useRef<HTMLDivElement>(null)
const focusAfter = useRef<string | null>(null)
useEffect(() => {
const target = focusAfter.current
if (!target) return
focusAfter.current = null
content.current
?.querySelector<HTMLButtonElement>(
target === "empty" ? "button" : `[data-remove="${target}"]`
)
?.focus()
}, [lines])
const step = (line: CartLine, quantity: number) => {
setQuantity(line.id, quantity)
setAnnouncement(COPY.quantityOf(line.name, quantity))
}
const drop = (line: CartLine) => {
const index = lines.findIndex((entry) => entry.id === line.id)
const neighbor = lines[index + 1] ?? lines[index - 1]
focusAfter.current = neighbor?.id ?? "empty"
remove(line.id)
setAnnouncement(`${cartLineLabel(line)} ${COPY.removed}`)
}
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>{COPY.title}</CardTitle>
</CardHeader>
<CardContent ref={content}>
<p role="status" className="sr-only">
{announcement}
</p>
{isEmpty ? (
<div className="flex flex-col items-start gap-3">
<p className="text-sm text-muted-foreground">{COPY.empty}</p>
<Button variant="outline" size="sm" onClick={reset}>
{COPY.reset}
</Button>
</div>
) : (
<ul role="list" className="flex flex-col divide-y">
{lines.map((line) => {
const [top, bottom] = SWATCHES[line.productId] ?? [
"var(--muted)",
"var(--muted)",
]
const max = line.maxQuantity ?? DEFAULT_MAX_QUANTITY
return (
<li
key={line.id}
className="flex items-center gap-3 py-3 first:pt-0 last:pb-0"
>
<span
aria-hidden="true"
className="size-10 shrink-0 rounded-md"
style={{
background: `linear-gradient(${top}, ${bottom})`,
}}
/>
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium">
{line.name}
</span>
<span className="truncate text-xs text-muted-foreground">
{line.options.join(", ")} ·{" "}
{formatMoney(cartLineAmount(line))}
</span>
</div>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="icon-xs"
aria-label={`${COPY.decrease} ${cartLineLabel(line)}`}
disabled={line.quantity <= 1}
onClick={() => step(line, line.quantity - 1)}
>
<MinusIcon />
</Button>
<span className="w-6 text-center text-sm tabular-nums">
{line.quantity}
</span>
<Button
variant="outline"
size="icon-xs"
aria-label={`${COPY.increase} ${cartLineLabel(line)}`}
disabled={line.quantity >= max}
onClick={() => step(line, line.quantity + 1)}
>
<PlusIcon />
</Button>
</div>
<Button
variant="ghost"
size="sm"
className="text-muted-foreground"
data-remove={line.id}
aria-label={`${COPY.remove} ${cartLineLabel(line)}`}
onClick={() => drop(line)}
>
{COPY.remove}
</Button>
</li>
)
})}
</ul>
)}
</CardContent>
{!isEmpty && (
<CardFooter className="border-t">
<dl className="grid w-full grid-cols-[1fr_auto] gap-y-1 text-sm tabular-nums">
<dt className="text-muted-foreground">{COPY.subtotal}</dt>
<dd>{formatMoney(totals.subtotal)}</dd>
<dt className="text-muted-foreground">{COPY.shipping}</dt>
<dd>
{totals.shipping === 0
? COPY.freeShipping
: formatMoney(totals.shipping)}
</dd>
<dt className="text-muted-foreground">{COPY.tax}</dt>
<dd>{formatMoney(totals.tax)}</dd>
<dt className="pt-1 font-medium">{COPY.total}</dt>
<dd className="pt-1 font-medium">{formatMoney(totals.total)}</dd>
</dl>
</CardFooter>
)}
</Card>
)
}
Installation
pnpm dlx shadcn@latest add @01orbital/use-cartnpx shadcn@latest add @01orbital/use-cartyarn dlx shadcn@latest add @01orbital/use-cartbunx --bun shadcn@latest add @01orbital/use-cartUsed in blocks
4 blocks are built with Use Cart:
Last updated on