Skip to main content

Installation

To start working with useDapp you need to have a working React environment.

To get started, add the following npm package @usedapp/core and its peer dependency in your project:

npm install @usedapp/core ethers

Example

Below is a simple example:

App.tsx
import React from 'react'
import ReactDOM from 'react-dom'

import { Mainnet, DAppProvider, useEtherBalance, useEthers, Config, Goerli } from '@usedapp/core'
import { formatEther } from '@ethersproject/units'
import { getDefaultProvider } from 'ethers'

const config: Config = {
readOnlyChainId: Mainnet.chainId,
readOnlyUrls: {
[Mainnet.chainId]: getDefaultProvider('mainnet'),
[Goerli.chainId]: getDefaultProvider('goerli'),
},
}

ReactDOM.render(
<DAppProvider config={config}>
<App />
</DAppProvider>,
document.getElementById('root')
)

const ConnectButton = () => {
const { account, deactivate, activateBrowserWallet } = useEthers()
// 'account' being undefined means that we are not connected.
if (account) return <button onClick={() => deactivate()}>Disconnect</button>
else return <button onClick={() => activateBrowserWallet()}>Connect</button>
}

function App() {
const { account, chainId } = useEthers()
const etherBalance = useEtherBalance(account)
if (chainId && !config.readOnlyUrls[chainId]) {
return <p>Please use either Mainnet or Goerli testnet.</p>
}

return (
<div>
<ConnectButton />
{etherBalance && (
<div className="balance">
<br />
Address:
<p className="bold">{account}</p>
<br />
Balance:
<p className="bold">{formatEther(etherBalance)}</p>
</div>
)}
</div>
)
}

A more comprehensive example is available here, with source code available here. Let's now go through the provided example in more details.

Setup

The first thing you need to do is set up DAppProvider with optional config and wrap your whole App in it. You can read about config here.

  <DAppProvider>
<App /> {/* Wrap your app with the Provider */}
</DAppProvider>

Connecting to a browser wallet

Then you need to activate the provider using activateBrowserWallet. It's best to do when the user clicks the "Connect" button.

  export function App() {
const { activateBrowserWallet, account } = useEthers()
return (
<div>
<div>
<button onClick={() => activateBrowserWallet()}>Connect</button>
</div>
{account && <p>Account: {account}</p>}
</div>
)
}

After the activation (i.e. user connects to a wallet like MetaMask) the component will show the user's address.

If you need to use another connector than a browser wallet, use the activate method from useEthers. See the web3-react doc for that one.