Usage

Usage

There are three parts to using use-cardano.

1. Wrap your app in the CardanoProvider

import { CardanoProvider, CardanoToaster } from "use-cardano"
 
const MyApp = () => {
  return (
    <CardanoProvider options={options}>
      <Content />
    </CardanoProvider>
  )
}

2. Use the components

import "use-cardano/styles/use-cardano.css"
import { CardanoWalletSelector, CardanoToaster } from "use-cardano"
 
const Content = () => {
  return (
    <div>
      <CardanoWalletSelector />
 
      <CardanoToaster />
    </div>
  )
}

3. Access state

import { useCardano } from "use-cardano"
 
const Component = () => {
  const { account } = useCardano()
 
  return (
    <div>
      <div>Connected Address: {account.address}</div>
    </div>
  )
}

Considerations

use-cardano has two peer dependencies that you'll need to install in your project, namely react and lucid. If you are looking to use this library, we assume that you are already familiar with React, and as for lucid, you can read more about it here.

A note on lucid

lucid is an ES module built in typescript with deno.js. This means that you'll need to use a bundler that support esm, typescript, and experimental features such as top-level await and WebAssembly and configure it accordingly.

By either using the Next.JS template or following the integrating into an existing project steps, you'll end up with a working version of this. For more information on lucid, visit their github page (opens in a new tab).

Usage of React.context

The library heavily relies on React Context (opens in a new tab). This makes it very easy to access the state of the library from anywhere in the component tree. However, it also means that there is a possible performance cost, as context updates are potentially expensive.

We have tried to mitigate this by using useMemo and useCallback to memoize the context values and functions, but it is not sure this is enough, since it's still to be proven. We don't forsee this being an issue, since the states should only update rarely, as the user interacts with the wallet provider, but if you experience performance related issues, please let us know by opening an issue (opens in a new tab).

UseCardanoConsumer

If you need to access the use-cardano context state directly, you can use the UseCardanoConsumer component. This is useful if you need to access the context state in a class component, and i'ts actually a more performant way of accessing the context state than using the useCardano hook, limiting the number of re-renders.

import { UseCardanoConsumer } from "use-cardano"
 
const Component = () => {
  return (
    <div>
      <UseCardanoConsumer>
        {({ account }) => <div>Connected Address: {account.address}</div>}
      </UseCardanoConsumer>
    </div>
  )
}