{"id":13428062,"url":"https://github.com/notrab/react-use-cart","last_synced_at":"2025-05-16T12:01:49.221Z","repository":{"id":39228836,"uuid":"219970052","full_name":"notrab/react-use-cart","owner":"notrab","description":"React hook library for managing cart state","archived":false,"fork":false,"pushed_at":"2025-05-09T04:22:32.000Z","size":924,"stargazers_count":375,"open_issues_count":11,"forks_count":49,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-05-09T05:25:38.897Z","etag":null,"topics":["cart","cart-items","cart-state","react-hook-library","shopping-cart"],"latest_commit_sha":null,"homepage":"http://npm.im/react-use-cart","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/notrab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["notrab"]}},"created_at":"2019-11-06T10:23:22.000Z","updated_at":"2025-04-26T18:38:07.000Z","dependencies_parsed_at":"2024-01-15T15:30:34.148Z","dependency_job_id":"9e2f7f35-b057-42d7-85aa-b6fe3d9addbb","html_url":"https://github.com/notrab/react-use-cart","commit_stats":{"total_commits":86,"total_committers":12,"mean_commits":7.166666666666667,"dds":"0.36046511627906974","last_synced_commit":"53c19fdcfa64208746fe868253b120a3a27ef1a2"},"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notrab%2Freact-use-cart","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notrab%2Freact-use-cart/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notrab%2Freact-use-cart/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/notrab%2Freact-use-cart/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/notrab","download_url":"https://codeload.github.com/notrab/react-use-cart/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254527072,"owners_count":22085917,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cart","cart-items","cart-state","react-hook-library","shopping-cart"],"created_at":"2024-07-31T01:00:45.224Z","updated_at":"2025-05-16T12:01:49.162Z","avatar_url":"https://github.com/notrab.png","language":"TypeScript","funding_links":["https://github.com/sponsors/notrab"],"categories":["Features","TypeScript"],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003e\n  react-use-cart\n\u003c/h1\u003e\n\u003cp align=\"center\"\u003e\n🛒 A lightweight shopping cart hook for React, Next.js, and Gatsby\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://npmjs.org/package/react-use-cart\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/v/react-use-cart.svg\" alt=\"Version\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://npmjs.org/package/react-use-cart\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dw/react-use-cart.svg\" alt=\"Downloads/week\" /\u003e\n  \u003c/a\u003e\n    \u003ca href=\"https://github.com/notrab/react-use-cart/blob/main/package.json\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/l/react-use-cart.svg\" alt=\"License\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/notrab/react-use-cart/network/members\"\u003e\n    \u003cimg src=\"https://img.shields.io/github/forks/notrab/react-use-cart\" alt=\"Forks on GitHub\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/notrab/react-use-cart/stargazers\"\u003e\n    \u003cimg src=\"https://img.shields.io/github/stars/notrab/react-use-cart\" alt=\"Forks on GitHub\" /\u003e\n  \u003c/a\u003e\n  \u003cimg src=\"https://badgen.net/bundlephobia/minzip/react-use-cart\" alt=\"minified + gzip size\" /\u003e\n  \u003c!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --\u003e\n  \u003cimg src=\"https://img.shields.io/badge/all_contributors-4-orange.svg\" alt=\"Contributors\" /\u003e\n  \u003c!-- ALL-CONTRIBUTORS-BADGE:END --\u003e\n\u003c/p\u003e\n\n## Why?\n\n- ![Bundle size](https://badgen.net/bundlephobia/minzip/react-use-cart)\n- **No dependencies**\n- 💳 Not tied to any payment gateway, or checkout - create your own!\n- 🔥 Persistent carts with local storage, or your own adapter\n- ⭐️ Supports multiples carts per page\n- 🛒 Flexible cart item schema\n- 🥞 Works with Next, Gatsby, React\n- ♻️ Trigger your own side effects with cart handlers (on item add, update, remove)\n- 🛠 Built with TypeScript\n- ✅ Fully tested\n- 🌮 Used by [Dines](https://dines.co.uk/?ref=react-use-cart)\n\n## Quick Start\n\n[Demo](https://codesandbox.io/s/react-use-cart-3c7vm)\n\n```js\nimport { CartProvider, useCart } from \"react-use-cart\";\n\nfunction Page() {\n  const { addItem } = useCart();\n\n  const products = [\n    {\n      id: 1,\n      name: \"Malm\",\n      price: 9900,\n      quantity: 1\n    },\n    {\n      id: 2,\n      name: \"Nordli\",\n      price: 16500,\n      quantity: 5\n    },\n    {\n      id: 3,\n      name: \"Kullen\",\n      price: 4500,\n      quantity: 1\n    },\n  ];\n\n  return (\n    \u003cdiv\u003e\n      {products.map((p) =\u003e (\n        \u003cdiv key={p.id}\u003e\n          \u003cbutton onClick={() =\u003e addItem(p)}\u003eAdd to cart\u003c/button\u003e\n        \u003c/div\u003e\n      ))}\n    \u003c/div\u003e\n  );\n}\n\nfunction Cart() {\n  const {\n    isEmpty,\n    totalUniqueItems,\n    items,\n    updateItemQuantity,\n    removeItem,\n  } = useCart();\n\n  if (isEmpty) return \u003cp\u003eYour cart is empty\u003c/p\u003e;\n\n  return (\n    \u003c\u003e\n      \u003ch1\u003eCart ({totalUniqueItems})\u003c/h1\u003e\n\n      \u003cul\u003e\n        {items.map((item) =\u003e (\n          \u003cli key={item.id}\u003e\n            {item.quantity} x {item.name} \u0026mdash;\n            \u003cbutton\n              onClick={() =\u003e updateItemQuantity(item.id, (item.quantity ?? 0) - 1)}\n            \u003e\n              -\n            \u003c/button\u003e\n            \u003cbutton\n              onClick={() =\u003e updateItemQuantity(item.id, (item.quantity ?? 0) + 1)}\n            \u003e\n              +\n            \u003c/button\u003e\n            \u003cbutton onClick={() =\u003e removeItem(item.id)}\u003e\u0026times;\u003c/button\u003e\n          \u003c/li\u003e\n        ))}\n      \u003c/ul\u003e\n    \u003c/\u003e\n  );\n}\n\nfunction App() {\n  return (\n    \u003cCartProvider\u003e\n      \u003cPage /\u003e\n      \u003cCart /\u003e\n    \u003c/CartProvider\u003e\n  );\n}\n```\n\n## Install\n\n```bash\nnpm install react-use-cart # yarn add react-use-cart\n```\n\n## `CartProvider`\n\nYou will need to wrap your application with the `CartProvider` component so that the `useCart` hook can access the cart state.\n\nCarts are persisted across visits using `localStorage`, unless you specify your own `storage` adapter.\n\n#### Usage\n\n```js\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { CartProvider } from \"react-use-cart\";\n\nReactDOM.render(\n  \u003cCartProvider\u003e{/* render app/cart here */}\u003c/CartProvider\u003e,\n  document.getElementById(\"root\")\n);\n```\n\n#### Props\n\n| Prop           | Required | Description                                                                                                                                                |\n| -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `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`. |\n| `onSetItems`   | _No_     | Triggered only when `setItems` invoked.                                                                                                                    |\n| `onItemAdd`    | _No_     | Triggered on items added to your cart, unless the item already exists, then `onItemUpdate` will be invoked.                                                |\n| `onItemUpdate` | _No_     | Triggered on items updated in your cart, unless you are setting the quantity to `0`, then `onItemRemove` will be invoked.                                  |\n| `onItemRemove` | _No_     | Triggered on items removed from your cart.                                                                                                                 |\n| `onEmptyCart` | _No_     | Triggered on empty cart.                                                                                                                 |\n| `storage`      | _No_     | Must return `[getter, setter]`.                                                                                                                            |\n| `metadata`     | _No_     | Custom global state on the cart. Stored inside of `metadata`.                                                                                              |\n## `useCart`\n\nThe `useCart` hook exposes all the getter/setters for your cart state.\n\n### `setItems(items)`\n\nThe `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.\n\n\n#### Args\n\n- `items[]` (**Required**): An array of cart item object. You must provide an `id` and `price` value for new items that you add to cart.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { setItems } = useCart();\n\nconst products = [\n  {\n    id: \"ckb64v21u000001ksgw2s42ku\",\n    name: \"Fresh Foam 1080v9\",\n    brand: \"New Balance\",\n    color: \"Neon Emerald with Dark Neptune\",\n    size: \"US 10\",\n    width: \"B - Standard\",\n    sku: \"W1080LN9\",\n    price: 15000,\n  },\n  {\n    id: \"cjld2cjxh0000qzrmn831i7rn\",\n    name: \"Fresh Foam 1080v9\",\n    brand: \"New Balance\",\n    color: \"Neon Emerald with Dark Neptune\",\n    size: \"US 9\",\n    width: \"B - Standard\",\n    sku: \"W1080LN9\",\n    price: 15000,\n  },\n];\n\nsetItems(products);\n```\n\n### `addItem(item, quantity)`\n\nThe `addItem` method should be used to add items to the cart.\n\n#### Args\n\n- `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.\n- `quantity` (_optional_, **default**: `1`): The amount of items you want to add.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { addItem } = useCart();\n\nconst product = {\n  id: \"cjld2cjxh0000qzrmn831i7rn\",\n  name: \"Fresh Foam 1080v9\",\n  brand: \"New Balance\",\n  color: \"Neon Emerald with Dark Neptune\",\n  size: \"US 9\",\n  width: \"B - Standard\",\n  sku: \"W1080LN9\",\n  price: 15000,\n};\n\naddItem(product, 2);\n```\n\n### `updateItem(itemId, data)`\n\nThe `updateItem` method should be used to update items in the cart.\n\n#### Args\n\n- `itemId` (**Required**): The cart item `id` you want to update.\n- `data` (**Required**): The updated cart item object.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { updateItem } = useCart();\n\nupdateItem(\"cjld2cjxh0000qzrmn831i7rn\", {\n  size: \"UK 10\",\n});\n```\n\n### `updateItemQuantity(itemId, quantity)`\n\nThe `updateItemQuantity` method should be used to update an items `quantity` value.\n\n#### Args\n\n- `itemId` (**Required**): The cart item `id` you want to update.\n- `quantity` (**Required**): The updated cart item quantity.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { updateItemQuantity } = useCart();\n\nupdateItemQuantity(\"cjld2cjxh0000qzrmn831i7rn\", 1);\n```\n\n### `removeItem(itemId)`\n\nThe `removeItem` method should be used to remove an item from the cart.\n\n#### Args\n\n- `itemId` (**Required**): The cart item `id` you want to remove.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { removeItem } = useCart();\n\nremoveItem(\"cjld2cjxh0000qzrmn831i7rn\");\n```\n\n### `emptyCart()`\n\nThe `emptyCart()` method should be used to remove all cart items, and resetting cart totals to the default `0` values.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { emptyCart } = useCart();\n\nemptyCart();\n```\n\n### `clearCartMetadata()`\n\nThe `clearCartMetadata()` will reset the `metadata` to an empty object.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { clearCartMetadata } = useCart();\n\nclearCartMetadata();\n```\n\n### `setCartMetadata(object)`\n\nThe `setCartMetadata()` will replace the `metadata` object on the cart. You must pass it an object.\n\n#### Args\n\n- `object`: A object with key/value pairs. The key being a string.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { setCartMetadata } = useCart();\n\nsetCartMetadata({ notes: \"This is the only metadata\" });\n```\n\n### `updateCartMetadata(object)`\n\nThe `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.\n\n#### Args\n\n- `object`: A object with key/value pairs. The key being a string.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { updateCartMetadata } = useCart();\n\nupdateCartMetadata({ notes: \"Leave in shed\" });\n```\n\n### `items = []`\n\nThis will return the current cart items in an array.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { items } = useCart();\n```\n\n### `isEmpty = false`\n\nA quick and easy way to check if the cart is empty. Returned as a boolean.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { isEmpty } = useCart();\n```\n\n### `getItem(itemId)`\n\nGet a specific cart item by `id`. Returns the item object.\n\n#### Args\n\n- `itemId` (**Required**): The `id` of the item you're fetching.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { getItem } = useCart();\n\nconst myItem = getItem(\"cjld2cjxh0000qzrmn831i7rn\");\n```\n\n### `inCart(itemId)`\n\nQuickly check if an item is in the cart. Returned as a boolean.\n\n#### Args\n\n- `itemId` (**Required**): The `id` of the item you're looking for.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { inCart } = useCart();\n\ninCart(\"cjld2cjxh0000qzrmn831i7rn\") ? \"In cart\" : \"Not in cart\";\n```\n\n### `totalItems = 0`\n\nThis returns the totaly quantity of items in the cart as an integer.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { totalItems } = useCart();\n```\n\n### `totalUniqueItems = 0`\n\nThis returns the total unique items in the cart as an integer.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { totalUniqueItems } = useCart();\n```\n\n### `cartTotal = 0`\n\nThis returns the total value of all items in the cart.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { cartTotal } = useCart();\n```\n\n### `metadata = {}`\n\nThis returns the metadata set with `updateCartMetadata`. This is useful for storing additional cart, or checkout values.\n\n#### Usage\n\n```js\nimport { useCart } from \"react-use-cart\";\n\nconst { metadata } = useCart();\n```\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/getTobiasNielsen\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/54803528?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eTobias Nielsen\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/notrab/react-use-cart/commits?author=getTobiasNielsen\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/craigtweedy\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/612558?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eCraig Tweedy\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/notrab/react-use-cart/commits?author=craigtweedy\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://jonathan.steele.pro\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/3578709?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eJonathan Steele\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/notrab/react-use-cart/commits?author=ynnoj\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://scottspence.com\"\u003e\u003cimg src=\"https://avatars.githubusercontent.com/u/234708?v=4?s=100\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eScott Spence\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"#example-spences10\" title=\"Examples\"\u003e💡\u003c/a\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\u003c!-- markdownlint-restore --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnotrab%2Freact-use-cart","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnotrab%2Freact-use-cart","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnotrab%2Freact-use-cart/lists"}