// src/cartStore.js import { create } from "zustand"; export const useCartStore = create((set) => ({ items: [], addToCart: (product) => set((state) => { const existing = state.items.find((i) => i.id === product.id); if (existing) { return { items: state.items.map((i) => i.id === product.id ? { ...i, quantity: i.quantity + 1 } : i ), }; } return { items: [...state.items, { ...product, quantity: 1 }] }; }), removeFromCart: (id) => set((state) => ({ items: state.items.filter((i) => i.id !== id) })), })); // src/App.jsx import { useCartStore } from "./cartStore"; const products = [ { id: 1, name: "Keyboard", price: 49.99 }, { id: 2, name: "Mouse", price: 19.99 }, ]; function ProductList() { const addToCart = useCartStore((state) => state.addToCart); return (
{products.map((product) => ( ))}
); } function CartDisplay() { const items = useCartStore((state) => state.items); const removeFromCart = useCartStore((state) => state.removeFromCart); return ( ); } function App() { return (
); } export default App; /* Notes: - addToCart's duplicate-check logic is identical to Project 6's Context version — only where the state lives and how components reach it has changed. - ProductList and CartDisplay each select only the slice of the store they actually need (addToCart vs items+removeFromCart), rather than reading the whole store and re-rendering on any change. */