Creating a cart in React JS

Creating a cart will be the hardest part when working on an Ecom-related project. Because we have manage multiple states for products, cart items, etc.

Building this from scratch is not a good idea. It's better if we use the Cart NPM Package.

The cart package provides a hook and different functions to make things easier.

In your react project root directory, run this command to add a cart package to the project dependency.

I'm using pnpm as my package manager. If you're using yarn or npm run the command correctly
#npm
npm install cart

#yarn
yarn add cart

#pnpm
pnpm add cart

Once the installation is done. Import the hook in your project file.

import { useCart } from "cart";

The hook provides different functions to add items to cart, remove from cart, etc

const { addToCart, decreaseItem, clearCart, cartItems } = useCart();

Let's say this is my product data array

const products = [
  {
      productId: "123",
      name: "Product 1",
      price: 10,
  },
  {
      productId: "456",
      name: "Product 2",
      price: 15,
  },
  // Add more products as needed
];

and I want to map everything in the UI, along with the Product Name, Add, and Remove buttons.

<ul>
  {products.map((product) => {
      const cartItem = cartItems.find(
          (item) => item.productId === product.productId,
      );
      const quantity = cartItem ? cartItem.quantity : 0;

      return (
          <>
              <li key={product.productId}>
                  {product.name} - <span>${product.price}</span> (x{quantity}) - $
                  {quantity * product.price}
                  <button onClick={() => addItem(product)}>+</button>
                  <button onClick={() => subtractItem(product.productId)}>
                      -
                  </button>
              </li>
              <br />
          </>
      );
  })}
</ul>

This will create something like this.

Now we have to add logic for the addItem button and subtract button.

// addItem function
const addItem = (product) => {
  addToCart({ ...product, quantity: 1 });
};

// subtract item function
const subtractItem = (productId) => {
  decreaseItem(productId, 1);
};

Both addToCart descreaseItem come from the useCart hook we imported earlier.

Now if you press the + and - button the cart will be updated.

Here is the demo you can try.

One good thing about this library is, that everything is stored locally in the user browser's local storage.

So If the user refreshes the page or closes and reopens it later, The item will be in the cart itself.

Using this library with Nextjs SSR will require some additional config. You can refer to the documentation.

If you have any doubts, please drop a comment.