Make sure you've installed ReservoirKit and followed the installation steps for adding a cart to your application.

This hook interacts with the CartProvider to expose the cart state and some useful methods to manage the cart.

import { useCart } from '@reservoir0x/reservoir-kit-ui'

  const { data, clear, clearTransaction, validate, remove, add, checkout } =
    useCart((cart) => cart)

The hook takes one parameter, which is a selector. To make the hook performant we've given developers the ability to select a piece of state to get updates on. This means that the hook won't trigger unnecessary rerenders. In the example above we select the whole state but if you simply want to just get the items you can do something like this:

import { useCart } from '@reservoir0x/reservoir-kit-ui'

  const { data: items } =
    useCart((cart) => cart.items)

The code above will just expose the items and only rerender when the items in the cart change. Let's dig into some of the methods returned by the hook:

MethodDescription
addYou can use this method to add multiple items to the cart. There are two interfaces that the method accepts. An array of tokens matching the interface from the tokens hook or a simplified interface where the cart needs to fetch the token data asynchronously. This could impact UX but is easier to implement in scenarios where the token info is not already prefetched. The second parameter the function takes is the chain id for the tokens.
removeYou can use this method for removing an item from the cart. Just pass an array of objects with an id property, which is just a combination of the token collection id and the token id delimited by a colon (:).
validateThis method validates the cart by checking if all the tokens have valid listings and also updates the OpenSea flagged status on each token.
checkoutUse this method to checkout valid tokens in the cart. If the transaction fails before being submitted then the tokens will not be removed from the cart. You can pass an object of options that map to the execute buy endpoint. Once this method is called the transaction object will be added to the cart which has information around the transaction hash and the status of the transaction. You can observe and react to this state to give your users an update on the pending transaction. Only one transaction is tracked at a time.
clearClears all the items in the cart.
clearTransactionClears the pending transaction.
import { useCart } from '@reservoir0x/reservoir-kit-ui'

  const { data, clear, clearTransaction, validate, remove, add, checkout } =
    useCart((cart) => cart)
  const tokens = useTokens({collection: "0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb"})

//add: Simplified interface
add([{id: "0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb:1"}], 1)

//add: Optimized interface
add([tokens[0]], 1)

remove(["0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb:1"])
checkout({ ...buyEndpointOptions })
validate()
clear()
clearTransaction()