react-use-cart

repository·main·Indexed 18 days ago

https://github.com/notrab/react-use-cart

A lightweight, dependency-free React hook library for managing shopping cart state in React, Next.js, and Gatsby applications. It provides a CartProvider for state management and persistence via localStorage, along with the useCart hook to handle adding, updating, and removing items, managing cart metadata, and tracking totals.

Tokens
2.5K
Snippets
11
Records
17
Agent score
14%

What's inside react-use-cart

  1. Use the useCart hook

    main

    The useCart hook provides access to the cart's state (items, totals, metadata) and methods to manipulate it (add, remove, update).

    import { useCart } from "react-use-cart";
    
    function MyComponent() {
      const { items, addItem, removeItem } = useCart();
      // ...
    }
  2. Set up the CartProvider

    main

    To enable the useCart hook, you must wrap your application (or the relevant part of your component tree) with the CartProvider component. By default, carts are persisted using localStorage.

    import React from "react";
    import ReactDOM from "react-dom";
    import { CartProvider } from "react-use-cart";
    
    ReactDOM.render(
      <CartProvider>{/* render app/cart here */}</CartProvider>,
      document.getElementById("root")
    );
  3. Configure CartProvider props

    main

    The CartProvider accepts several props to customize cart behavior and lifecycle hooks:

    PropRequiredDescription
    idNoUnique id for the cart. Enables automatic retrieval via localStorage and allows multiple cart instances on one page.
    onSetItemsNoTriggered when setItems is invoked.
    onItemAddNoTriggered when items are added (unless the item exists, then onItemUpdate triggers).
    onItemUpdateNoTriggered when items are updated (unless quantity is set to 0, then onItemRemove triggers).
    onItemRemoveNoTriggered when items are removed.
    onEmptyCartNoTriggered when the cart becomes empty.
    storageNoA custom storage adapter. Must return [getter, setter].
    metadataNoCustom global state stored inside the metadata object.
  4. Setup the CartProvider

    main

    To use react-use-cart, you must wrap your application (or the relevant part of your component tree) with the CartProvider. This component manages the cart state and provides it to all child components via the useCart hook.

    By default, it uses useLocalStorage to persist the cart state. You can customize the behavior using several props:

    • id: A unique identifier for the cart. If not provided, a random one is generated.
    • defaultItems: An array of Item objects to initialize the cart.
    • metadata: Initial metadata for the cart.
    • storage: A custom storage function (defaults to useLocalStorage) that follows the signature (key: string, initialValue: string) => [string, (value: Function | string) => void].
    • onSetItems, onItemAdd, onItemUpdate, onItemRemove, onEmptyCart: Callback functions triggered when specific cart actions occur.
    import { CartProvider } from 'react-use-cart';
    
    function App() {
      return (
        <CartProvider id="my-cart-id">
          <YourAppContent />
        </CartProvider>
      );
    }
  5. Manage cart metadata with useCart

    main

    Metadata allows you to store additional custom key/value pairs on the cart object (e.g., checkout notes or user preferences).

    • setCartMetadata(object): Replaces the entire metadata object with the provided object.
    • updateCartMetadata(object): Merges the provided object into the existing metadata.
    • clearCartMetadata(): Resets metadata to an empty object {}.
    const { setCartMetadata, updateCartMetadata, clearCartMetadata } = useCart();
    
    setCartMetadata({ notes: "This is the only metadata" });
    updateCartMetadata({ notes: "Leave in shed" }); // Merges/Updates
    clearCartMetadata();
  6. Manage cart items with useCart methods

    main

    Use these methods to manipulate the contents of the cart:

    • setItems(items[]): Overwrites the entire cart with a new array of items. Each item must have an id and price. If no quantity is provided, it defaults to 1.
    • addItem(item, quantity?): Adds an item to the cart. The item must have an id and price. quantity defaults to 1.
    • updateItem(itemId, data): Updates specific properties of an existing item using its id.
    • updateItemQuantity(itemId, quantity): Directly updates the quantity of a specific item.
    • removeItem(itemId): Removes an item from the cart entirely.
    • emptyCart(): Removes all items and resets all totals to 0.
    const { 
      setItems, 
      addItem, 
      updateItem, 
      updateItemQuantity, 
      removeItem, 
      emptyCart 
    } = useCart();
    
    // Examples
    setItems([{ id: '1', name: 'Product', price: 100 }]);
    addItem({ id: '2', name: 'Product 2', price: 200 }, 2);
    updateItem('1', { name: 'Updated Name' });
    updateItemQuantity('1', 5);
    removeItem('1');
    emptyCart();
  7. Access cart state and totals with useCart

    main

    The useCart hook returns several properties to inspect the current state:

    PropertyTypeDescription
    itemsArrayThe current array of cart item objects.
    isEmptybooleantrue if the cart has no items.
    totalItemsnumberThe sum of all item quantities in the cart.
    totalUniqueItemsnumberThe number of unique item IDs in the cart.
    cartTotalnumberThe total monetary value of all items in the cart.
    metadataObjectThe current metadata object.
    getItem(itemId)functionReturns the item object for the given id.
    inCart(itemId)functionReturns true if the item is in the cart.
  8. Add items to the cart with addItem()

    main

    Use addItem(item, quantity) to add a new item or increase the quantity of an existing item in the cart.

    • item: An object conforming to the Item interface. It must have an id and a price if it is a new item.
    • quantity: (Optional) The amount to add. Defaults to 1.

    If the item already exists in the cart, addItem will increment the existing quantity rather than adding a duplicate entry.

    const { addItem } = useCart();
    
    const handleAdd = () => {
      addItem({ id: 'p1', price: 10, name: 'Product 1' }, 2);
    };
  9. Use the useCart hook to manage cart state

    main

    The useCart hook allows you to access the current cart state and all available cart manipulation methods from any component wrapped within a CartProvider.

    Warning: If you call useCart in a component that is not a child of CartProvider, it will throw an error: "Expected to be wrapped in a CartProvider".

    import { useCart } from 'react-use-cart';
    
    const CartSummary = () => {
      const { items, cartTotal, totalItems } = useCart();
      
      return (
        <div>
          <p>Total Items: {totalItems}</p>
          <p>Total Price: {cartTotal}</p>
        </div>
      );
    };