• Stars
    star
    331
  • Rank 127,323 (Top 3 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React hook library for managing cart state

react-use-cart

🛒 A lightweight shopping cart hook for React, Next.js, and Gatsby

Version Downloads/week License Forks on GitHub Forks on GitHub minified + gzip size Contributors

Why?

  • Bundle size
  • No dependencies
  • 💳 Not tied to any payment gateway, or checkout - create your own!
  • 🔥 Persistent carts with local storage, or your own adapter
  • ⭐️ Supports multiples carts per page
  • 🛒 Flexible cart item schema
  • 🥞 Works with Next, Gatsby, React
  • ♻️ Trigger your own side effects with cart handlers (on item add, update, remove)
  • 🛠 Built with TypeScript
  • Fully tested
  • 🌮 Used by Dines

Quick Start

Demo

import { CartProvider, useCart } from "react-use-cart";

function Page() {
  const { addItem } = useCart();

  const products = [
    {
      id: 1,
      name: "Malm",
      price: 9900,
      quantity: 1
    },
    {
      id: 2,
      name: "Nordli",
      price: 16500,
      quantity: 5
    },
    {
      id: 3,
      name: "Kullen",
      price: 4500,
      quantity: 1
    },
  ];

  return (
    <div>
      {products.map((p) => (
        <div key={p.id}>
          <button onClick={() => addItem(p)}>Add to cart</button>
        </div>
      ))}
    </div>
  );
}

function Cart() {
  const {
    isEmpty,
    totalUniqueItems,
    items,
    updateItemQuantity,
    removeItem,
  } = useCart();

  if (isEmpty) return <p>Your cart is empty</p>;

  return (
    <>
      <h1>Cart ({totalUniqueItems})</h1>

      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.quantity} x {item.name} &mdash;
            <button
              onClick={() => updateItemQuantity(item.id, item.quantity - 1)}
            >
              -
            </button>
            <button
              onClick={() => updateItemQuantity(item.id, item.quantity + 1)}
            >
              +
            </button>
            <button onClick={() => removeItem(item.id)}>&times;</button>
          </li>
        ))}
      </ul>
    </>
  );
}

function App() {
  return (
    <CartProvider>
      <Page />
      <Cart />
    </CartProvider>
  );
}

Install

npm install react-use-cart # yarn add react-use-cart

CartProvider

You will need to wrap your application with the CartProvider component so that the useCart hook can access the cart state.

Carts are persisted across visits using localStorage, unless you specify your own storage adapter.

Usage

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")
);

Props

Prop Required Description
id No id for your cart to enable automatic cart retrieval via window.localStorage. If you pass a id then you can use multiple instances of CartProvider.
onSetItems No Triggered only when setItems invoked.
onItemAdd No Triggered on items added to your cart, unless the item already exists, then onItemUpdate will be invoked.
onItemUpdate No Triggered on items updated in your cart, unless you are setting the quantity to 0, then onItemRemove will be invoked.
onItemRemove No Triggered on items removed from your cart.
storage No Must return [getter, setter].
metadata No Custom global state on the cart. Stored inside of metadata.

useCart

The useCart hook exposes all the getter/setters for your cart state.

setItems(items)

The setItems method should be used to set all items in the cart. This will overwrite any existing cart items. A quantity default of 1 will be set for an item implicitly if no quantity is specified.

Args

  • items[] (Required): An array of cart item object. You must provide an id and price value for new items that you add to cart.

Usage

import { useCart } from "react-use-cart";

const { setItems } = useCart();

const products = [
  {
    id: "ckb64v21u000001ksgw2s42ku",
    name: "Fresh Foam 1080v9",
    brand: "New Balance",
    color: "Neon Emerald with Dark Neptune",
    size: "US 10",
    width: "B - Standard",
    sku: "W1080LN9",
    price: 15000,
  },
  {
    id: "cjld2cjxh0000qzrmn831i7rn",
    name: "Fresh Foam 1080v9",
    brand: "New Balance",
    color: "Neon Emerald with Dark Neptune",
    size: "US 9",
    width: "B - Standard",
    sku: "W1080LN9",
    price: 15000,
  },
];

setItems(products);

addItem(item, quantity)

The addItem method should be used to add items to the cart.

Args

  • item (Required): An object that represents your cart item. You must provide an id and price value for new items that you add to cart.
  • quantity (optional, default: 1): The amount of items you want to add.

Usage

import { useCart } from "react-use-cart";

const { addItem } = useCart();

const product = {
  id: "cjld2cjxh0000qzrmn831i7rn",
  name: "Fresh Foam 1080v9",
  brand: "New Balance",
  color: "Neon Emerald with Dark Neptune",
  size: "US 9",
  width: "B - Standard",
  sku: "W1080LN9",
  price: 15000,
};

addItem(product, 2);

updateItem(itemId, data)

The updateItem method should be used to update items in the cart.

Args

  • itemId (Required): The cart item id you want to update.
  • data (Required): The updated cart item object.

Usage

import { useCart } from "react-use-cart";

const { updateItem } = useCart();

updateItem("cjld2cjxh0000qzrmn831i7rn", {
  size: "UK 10",
});

updateItemQuantity(itemId, quantity)

The updateItemQuantity method should be used to update an items quantity value.

Args

  • itemId (Required): The cart item id you want to update.
  • quantity (Required): The updated cart item quantity.

Usage

import { useCart } from "react-use-cart";

const { updateItemQuantity } = useCart();

updateItemQuantity("cjld2cjxh0000qzrmn831i7rn", 1);

removeItem(itemId)

The removeItem method should be used to remove an item from the cart.

Args

  • itemId (Required): The cart item id you want to remove.

Usage

import { useCart } from "react-use-cart";

const { removeItem } = useCart();

removeItem("cjld2cjxh0000qzrmn831i7rn");

emptyCart()

The emptyCart() method should be used to remove all cart items, and resetting cart totals to the default 0 values.

Usage

import { useCart } from "react-use-cart";

const { emptyCart } = useCart();

emptyCart();

clearCartMetadata()

The clearCartMetadata() will reset the metadata to an empty object.

Usage

import { useCart } from "react-use-cart";

const { clearCartMetadata } = useCart();

clearCartMetadata();

setCartMetadata(object)

The setCartMetadata() will replace the metadata object on the cart. You must pass it an object.

Args

  • object: A object with key/value pairs. The key being a string.

Usage

import { useCart } from "react-use-cart";

const { setCartMetadata } = useCart();

setCartMetadata({ notes: "This is the only metadata" });

updateCartMetadata(object)

The updateCartMetadata() will update the metadata object on the cart. You must pass it an object. This will merge the passed object with the existing metadata.

Args

  • object: A object with key/value pairs. The key being a string.

Usage

import { useCart } from "react-use-cart";

const { updateCartMetadata } = useCart();

updateCartMetadata({ notes: "Leave in shed" });

items = []

This will return the current cart items in an array.

Usage

import { useCart } from "react-use-cart";

const { items } = useCart();

isEmpty = false

A quick and easy way to check if the cart is empty. Returned as a boolean.

Usage

import { useCart } from "react-use-cart";

const { isEmpty } = useCart();

getItem(itemId)

Get a specific cart item by id. Returns the item object.

Args

  • itemId (Required): The id of the item you're fetching.

Usage

import { useCart } from "react-use-cart";

const { getItem } = useCart();

const myItem = getItem("cjld2cjxh0000qzrmn831i7rn");

inCart(itemId)

Quickly check if an item is in the cart. Returned as a boolean.

Args

  • itemId (Required): The id of the item you're looking for.

Usage

import { useCart } from "react-use-cart";

const { inCart } = useCart();

inCart("cjld2cjxh0000qzrmn831i7rn") ? "In cart" : "Not in cart";

totalItems = 0

This returns the totaly quantity of items in the cart as an integer.

Usage

import { useCart } from "react-use-cart";

const { totalItems } = useCart();

totalUniqueItems = 0

This returns the total unique items in the cart as an integer.

Usage

import { useCart } from "react-use-cart";

const { totalUniqueItems } = useCart();

cartTotal = 0

This returns the total value of all items in the cart.

Usage

import { useCart } from "react-use-cart";

const { cartTotal } = useCart();

metadata = {}

This returns the metadata set with updateCartMetadata. This is useful for storing additional cart, or checkout values.

Usage

import { useCart } from "react-use-cart";

const { metadata } = useCart();

Contributors

Thanks goes to these wonderful people (emoji key):


Tobias Nielsen

💻

Craig Tweedy

💻

Jonathan Steele

💻

Scott Spence

💡

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

create-react-app-redux

React Router, Redux, Redux Thunk & Create React App boilerplate
JavaScript
919
star
2

headless-dropshipping-starter

Create your own dropshipping store with Next.js, Snipcart & Printful 👕
TypeScript
715
star
3

commerceql

UNMAINTAINED
JavaScript
212
star
4

fakerql

Hosted faker GraphQL endpoint for frontend developers
TypeScript
149
star
5

awesome-headless-commerce

A community curated list of headless commerce APIs, products, and services. A heads-up for modern store builders.
117
star
6

jamstackbb

Simple forum software powered by Next.js and GraphQL.
JavaScript
48
star
7

chatbase

TypeScript
38
star
8

graphql-server-tutorial

JavaScript
33
star
9

graphql.wtf

Learn something new with GraphQL, every week 👇🏻
TypeScript
29
star
10

nextjs-commercejs-example

JavaScript
16
star
11

nextjs-tailwindcss-starter

JavaScript
15
star
12

graphqlconf-2019

Website implementation of GraphQL Conf 2019
JavaScript
15
star
13

printful-request

JavaScript
14
star
14

apollo-federation-zeit-now-demo

JavaScript
12
star
15

graphcms-nextjs-example

JavaScript
11
star
16

nuxtjs-commercejs-example

Vue
9
star
17

apollo-datasource-givefood

🥫 Apollo data source for GiveFood API.
JavaScript
8
star
18

nextjs-stripe-intents

JavaScript
8
star
19

gatsby-source-transistorfm

🎙 Gatsby source plugin for fetching show and episode data from Transistor
JavaScript
8
star
20

producthunt-graphql-layer-clone

JavaScript
7
star
21

express-babel-starter

🔥 Babel / ExpressJS Starter Kit
JavaScript
7
star
22

dotfiles

My dotfiles ⚡️
Shell
6
star
23

create-react-app-apollo-redux

Get started using React with Redux & Apollo.
JavaScript
6
star
24

styledbyme-tutorial

https://www.youtube.com/watch?v=u6gQ48rSw-E
JavaScript
6
star
25

graphql.wtf-type-safe-resolver-codegen

TypeScript
6
star
26

react-graphql

JavaScript
6
star
27

cmsly

Build your own branded short links with GraphCMS & Vercel
JavaScript
6
star
28

next-graphql-handler

JavaScript
5
star
29

chec-request

Lightweight Chec eCommerce client for Node, browsers and serverless functions
JavaScript
5
star
30

gatsby-source-chec-example

JavaScript
4
star
31

graphcms-migrate

JavaScript
4
star
32

now-next-graphql-monorepo

JavaScript
4
star
33

graphql.wtf-graphql-helix-nextjs

JavaScript
4
star
34

zeit-apollo-server

JavaScript
4
star
35

page-reactions-with-sveltekit

Svelte
3
star
36

shortcuts

Handlebars
3
star
37

frontendne-graphql-demo

JavaScript
3
star
38

graphtools-tutorial-code

JavaScript
3
star
39

create-react-app-hapi

JavaScript
3
star
40

apollo-modules-example

JavaScript
3
star
41

create-react-app-apollo

HTML
3
star
42

micro-stripe-charge

JavaScript
3
star
43

graphql.wtf-merging-resolvers

JavaScript
3
star
44

gatsby-source-trackingmore

Gatsby source plugin for fetching carriers from Trackingmore.com
JavaScript
3
star
45

graphql.wtf-remix-graphql

JavaScript
3
star
46

dynamic-graphql-nextjs-forms

JavaScript
2
star
47

commercejs-graphql-server

JavaScript
2
star
48

moltin-graphql-storefront-example

JavaScript
2
star
49

graphcms-remix-starter

TypeScript
2
star
50

graphiqlbin

JavaScript
2
star
51

sapper-commercejs-example

JavaScript
2
star
52

gatsby-theme-transistorfm

🎙 Gatsby theme for Transistor
JavaScript
2
star
53

apollo-server-givefood

Make requests to Give Food API using GraphQL.
JavaScript
2
star
54

gatsby-starter-netlify-cms

JavaScript
2
star
55

graphcms-gatsby-source-graphql

JavaScript
2
star
56

gatsby-plugin-statickit

JavaScript
2
star
57

graphql.wtf-graphql-codegen-apollo-client

TypeScript
2
star
58

next-commerce

1
star
59

use-snipcart

TypeScript
1
star
60

sanity-gatsby-blog

Blog with Gatsby
JavaScript
1
star
61

graphql.wtf-graphql-yoga

TypeScript
1
star
62

getwalter

Ruby
1
star
63

graphsale-dashboard

JavaScript
1
star
64

testtt

1
star
65

graphql.wtf-graphql-yoga-2

TypeScript
1
star
66

graphql.wtf-sdl-descriptions

TypeScript
1
star
67

babel-pkg-starter

JavaScript
1
star
68

graphql.wtf-serverless-graphql-vercel

JavaScript
1
star
69

notrab

1
star
70

productshare

Build a voting platform in 7 days.
Ruby
1
star
71

graphql.wtf-remote-schema-stitching

JavaScript
1
star
72

gatsby-theme-cart

🛒 A drop-in shopping cart theme for Gatsby
JavaScript
1
star
73

moltin-digital-file-delivery

WIP
JavaScript
1
star
74

gatsby-graphcms-snipcart-starter

JavaScript
1
star
75

norsound.com

JavaScript
1
star
76

apollo-datasources-graphcms-example

JavaScript
1
star
77

image-transformation-directive

1
star
78

graphql.wtf-kitql

TypeScript
1
star
79

express-examples

JavaScript
1
star
80

now-api-starter

TypeScript
1
star
81

graphql-in-a-rest-world-talk

JavaScript
1
star
82

moltin-react-checkout

JavaScript
1
star
83

micro-infrastructure-talk

JavaScript
1
star
84

graphql.wtf-authorization-with-graphql-shield

JavaScript
1
star
85

nextjs-styled-components-semantic-ui

JavaScript
1
star
86

moltin-cli2

JavaScript
1
star
87

react-redux-express-starter

Boiler plate code for getting started with Create React App + Redux + Express
JavaScript
1
star
88

tailwind-dark-mode-switcher-example

JavaScript
1
star
89

moltin-graphql-checkout

TypeScript
1
star
90

react-stick-it

JavaScript
1
star
91

vue-commercejs

JavaScript
1
star
92

graphql.wtf-envelop-response-cache

TypeScript
1
star
93

video-graphql-middleware

JavaScript
1
star
94

gatsby-theme-graphcms-docs

JavaScript
1
star
95

graphql.wtf-error-handling-union-types

TypeScript
1
star
96

sentry-integration-libsql-client

TypeScript
1
star
97

shopkit

Moltin Shopkit is a minimalist component library that enables developers to easily embed commerce inside applications built with React.
JavaScript
1
star