React Hooks


Quickstart with Injected Wallets and Ethers Provider

Install Modules

npm i @web3-onboard/react @web3-onboard/injected-wallets ethers
yarn add @web3-onboard/react @web3-onboard/injected-wallets ethers

Add Code

**For a live example checkout our React Demo code base or try it live here
import React from 'react'
import { init, useConnectWallet } from '@web3-onboard/react'
import injectedModule from '@web3-onboard/injected-wallets'
import { ethers } from 'ethers'
const injected = injectedModule()
const rpcApiKey = '<ALCHEMY_KEY>' || '<INFURA_KEY>'
const rpcUrl = `${rpcApiKey}` || `${rpcApiKey}`
// initialize Onboard
wallets: [injected],
chains: [
id: '0x1',
token: 'ETH',
label: 'Ethereum Mainnet',
function App() {
const [{ wallet, connecting }, connect, disconnect] = useConnectWallet()
// create an ethers provider
let ethersProvider
if (wallet) {
ethersProvider = new ethers.providers.Web3Provider(wallet.provider, 'any')
return (
onClick={() => (wallet ? disconnect() : connect())}
{connecting ? 'connecting' : wallet ? 'disconnect' : 'connect'}


The init function must be called before any hooks can be used. The init function just initializes web3-onboard and makes it available for all hooks to use. For reference check out the initialization docs for @web3-onboard/core


This hook allows you to connect the user's wallet and track the state of the connection status and the wallet that is connected.
import { useConnectWallet } from '@web3-onboard/react'
type UseConnectWallet = (): [
{ wallet: WalletState | null; connecting: boolean },
(options: ConnectOptions) => Promise<void>,
(wallet: DisconnectOptions) => Promise<void>,
(addresses?: string[]) => Promise<void>,
(wallets: WalletInit[]) => void
type ConnectOptions = {
autoSelect?: string // wallet name to autoselect for user
type DisconnectOptions = {
label: string // wallet label
type WalletState = {
label: string
icon: string
provider: EIP1193Provider
accounts: Account[]
chains: ConnectedChain[]
instance?: unknown
type WalletInit = (helpers: WalletHelpers) => WalletModule | WalletModule[] | null;
const [
wallet, // the wallet that has been connected or null if not yet connected
connecting // boolean indicating if connection is in progress
connect, // function to call to initiate user to connect wallet
disconnect, // function to call to with wallet<DisconnectOptions> to disconnect wallet
updateBalances, // function to be called with an optional array of wallet addresses connected through Onboard to update balance or empty/no params to update all connected wallets
setWalletModules // function to be called with an array of wallet modules to conditionally allow connection of wallet types i.e. setWalletModules([ledger, trezor, injected])
setPrimaryWallet // function that can set the primary wallet and/or primary account within that wallet. The wallet that is set needs to be passed in for the first parameter and if you would like to set the primary account, the address of that account also needs to be passed in
] = useConnectWallet()
setPrimaryWallet The primary wallet (first in the list of connected wallets) and primary account (first in the list of connected accounts for a wallet) can be set by using the setPrimaryWallet function. The wallet that is set needs to be passed in for the first parameter and if you would like to set the primary account, the address of that account also needs to be passed in:
// set the second wallet in the wallets array as the primary
// set the second wallet in the wallets array as the primary wallet
// as well as setting the third account in that wallet as the primary account


This hook allows you to set the chain of a user's connected wallet, keep track of the current chain the user is connected to and the status of setting the chain. Passing in a wallet label will operate on that connected wallet, otherwise it will default to the last connected wallet.
import { useSetChain } from '@web3-onboard/react'
type UseSetChain = (
walletLabel?: string
): [
chains: Chain[]
connectedChain: ConnectedChain | null
settingChain: boolean
(options: SetChainOptions) => Promise<void>
type SetChainOptions = {
chainId: string
chainNamespace?: string
wallet?: WalletState['label']
const [
chains, // the list of chains that web3-onboard was initialized with
connectedChain, // the current chain the user's wallet is connected to
settingChain // boolean indicating if the chain is in the process of being set
setChain // function to call to initiate user to switch chains in their wallet
] = useSetChain()


This hook allows the dev to access all notifications if enabled, send custom notifications and update notify <enable/disable & update transactionHandler function> note requires an API key be added to the initialization, enabled by default if API key exists
import { useNotifications } from '@web3-onboard/react'
type UseNotifications = (): [
(updatedNotification: CustomNotification) => {
dismiss: () => void
update: UpdateNotification
(update: Partial<Notify>) => void
type Notification = {
id: string
key: string
type: NotificationType
network: Network
startTime?: number
eventCode: string
message: string
autoDismiss: number
link?: string
onClick?: (event: Event) => void
type TransactionHandlerReturn =
| CustomNotification
| boolean
| void
type CustomNotification = Partial<
Omit<Notification, 'startTime' | 'network' | 'id' | 'key'>
type CustomNotificationUpdate = Partial<
Omit<Notification, 'startTime' | 'network'>
type NotificationType = 'pending' | 'success' | 'error' | 'hint'
interface UpdateNotification {
(notificationObject: CustomNotification): {
dismiss: () => void
update: UpdateNotification
type PreflightNotificationsOptions = {
sendTransaction?: () => Promise<string | void>
estimateGas?: () => Promise<string>
gasPrice?: () => Promise<string>
balance?: string | number
txDetails?: TxDetails
txApproveReminderTimeout?: number
type TxDetails = {
value: string | number
to?: string
from?: string
type Notify = {
* Defines whether to subscribe to transaction events or not
* default: true
enabled?: boolean
* Callback that receives all transaction events
* Return a custom notification based on the event
* Or return false to disable notification for this event
* Or return undefined for a default notification
transactionHandler: (
event: EthereumTransactionData
) => TransactionHandlerReturn
const [
notifications, // the list of all notifications that update when notifications are added, updated or removed
customNotification, // a function that takes a customNotification object and allows custom notifications to be shown to the user, returns an update and dismiss callback
updateNotify, // a function that takes a Notify object to allow updating of the properties
preflightNotifications // a function that takes a PreflightNotificationsOption to create preflight notifications
] = useNotifications()
// View notifications as they come in if you would like to handle them independent of the notification display
useEffect(() => {
}, [notifications])
// Custom notification example
onClick={() => {
const { update } =
eventCode: 'dbUpdate',
type: 'hint',
message: 'Custom hint notification created by the dapp',
onClick: () =>``)
// Update your notification example below
() =>
eventCode: 'dbUpdateSuccess',
message: 'Hint notification reason resolved!',
type: 'success',
autoDismiss: 5000
Custom Hint Notification
updateNotify If you need to update your notify configuration after initialization, you can do that by calling the updateNotify function:
customNotification Notify can be used to deliver custom DApp notifications by passing a CustomNotification object to the customNotification action. This will return an UpdateNotification type. This UpdateNotification will return an update function that can be passed a new CustomNotification to update the existing notification. The customNotification method also returns a dismiss method that is called without any parameters to dismiss the notification.
preflightNotifications Notify can be used to deliver standard notifications along with preflight information by passing a PreflightNotificationsOptions object to the preflightNotifications action. This will return a a promise that resolves to the transaction hash (if sendTransaction resolves the transaction hash and is successful), the internal notification id (if no sendTransaction function is provided) or return nothing if an error occurs or sendTransaction is not provided or doesn't resolve to a string.
Preflight event types include
  • txRequest : Alert user there is a transaction request awaiting confirmation by their wallet
  • txAwaitingApproval : A previous transaction is awaiting confirmation
  • txConfirmReminder : Reminder to confirm a transaction to continue - configurable with the txApproveReminderTimeout property; defaults to 15 seconds
  • nsfFail : The user has insufficient funds for transaction (requires gasPrice, estimateGas, balance, txDetails.value)
  • txError : General transaction error (requires sendTransaction)
  • txSendFail : The user rejected the transaction (requires sendTransaction)
  • txUnderpriced : The gas price for the transaction is too low (requires sendTransaction)


This hook allows you to track the state of all the currently connected wallets.
import { useWallets } from '@web3-onboard/react'
type UseWallets = (): WalletState[]
const connectedWallets = useWallets()


This hook allows you to track and update the state of the AccountCenter
import { useAccountCenter } from '@web3-onboard/react'
type UseAccountCenter = (): ((
update: AccountCenter | Partial<AccountCenter>
) => void)
type AccountCenterPosition =
| 'topRight'
| 'bottomRight'
| 'bottomLeft'
| 'topLeft'
type AccountCenter = {
enabled: boolean
position?: AccountCenterPosition
expanded?: boolean
minimal?: boolean
const updateAccountCenter = useAccountCenter()


This hook allows you to set the locale of your application to allow language updates associated with the i18n config
import { useSetLocale } from '@web3-onboard/react'
type useSetLocale = (): ((locale: string) => void)
const updateLocale = useSetLocale()

Build Environments

Many of the wallet modules require dependencies that are not normally included in browser builds (namely the node builtin modules such as crypto, buffer, util etc). If you are having build issues you can try the following bundler configs to resolve these dependency issues:

Webpack 4

Everything should just work since the node builtins are automatically bundled in v4

Webpack 5

You'll need to add some dev dependencies with the following command:
npm i --save-dev assert buffer crypto-browserify stream-http https-browserify os-browserify process stream-browserify util stream
Then add the following to your webpack.config.js file:
const webpack = require('webpack')
module.exports = {
resolve: {
alias: {
assert: 'assert',
buffer: 'buffer',
crypto: 'crypto-browserify',
http: 'stream-http',
https: 'https-browserify',
os: 'os-browserify/browser',
process: 'process/browser',
stream: 'stream-browserify',
util: 'util'
experiments: {
asyncWebAssembly: true
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer']
If using create-react-app
CRACO provides an easy way to override webpack config which is obfuscated in Create React App built applications.
The above webpack 5 example can be used in the craco.config.js file at the root level in this case.
Last modified 1mo ago
Copy link
On this page
Quickstart with Injected Wallets and Ethers Provider
Install Modules
Add Code
Build Environments