DEV Community

Cover image for Wagmi: React Hooks for Ethereum
Hasret Özkan
Hasret Özkan

Posted on

Wagmi: React Hooks for Ethereum

Wagmi is a collection of React Hooks containing everything you need to start working with Ethereum. wagmi makes it easy to "Connect Wallet" display ENS and balance information, sign messages, interact with contracts, and much more - all with caching, request deduplication, and persistence.

Installation

You can install wagmi.sh with these codes.

npm i wagmi ethers
Enter fullscreen mode Exit fullscreen mode

or

yarn add wagmi ethers
Enter fullscreen mode Exit fullscreen mode

Quick Start

You can start with importing wagmi.sh.

import { WagmiConfig, createClient } from 'wagmi'
import { getDefaultProvider } from 'ethers'

const client = createClient({
  autoConnect: true,
  provider: getDefaultProvider(),
})

function App() {
  return (
    <WagmiConfig client={client}>
      <Profile />
    </WagmiConfig>
  )
}
Enter fullscreen mode Exit fullscreen mode

Then you can connect wallet with these hook methods. Also more example on website and documantation.

import { useAccount, useConnect, useDisconnect } from 'wagmi'
import { InjectedConnector } from 'wagmi/connectors/injected'

function Profile() {
  const { address, isConnected } = useAccount()
  const { connect } = useConnect({
    connector: new InjectedConnector(),
  })
  const { disconnect } = useDisconnect()

  if (isConnected)
    return (
      <div>
        Connected to {address}
        <button onClick={() => disconnect()}>Disconnect</button>
      </div>
    )
  return <button onClick={() => connect()}>Connect Wallet</button>
}
Enter fullscreen mode Exit fullscreen mode

In this example, we create a wagmi Client and pass it to the WagmiConfig React Context. The client is set up to use the ethers Default Provider and automatically connect to previously connected wallets.
Next, we use the useConnect hook to connect an injected wallet (e.g. MetaMask) to the app. Finally, we show the connected account's address with useAccount and allow them to disconnect with useDisconnect.

Features

Wagmi supports all these features out-of-the-box:

  • 20+ hooks for working with wallets, ENS, contracts, transactions, signing, etc.
  • Built-in wallet connectors for MetaMask, WalletConnect, Coinbase Wallet, and Injected
  • Caching, request deduplication, multicall, batching, and persistence
  • Auto-refresh data on wallet, block, and network changes
  • TypeScript ready
  • Test suite running against forked Ethereum network

…and a lot more.

Summary

Wagmi is so easy to use for react. Also it solves a lot of problems and make everything easier for developer. You can read documantation. Also you can check more examples.

See you in next article. Also you can follow me on LinkedIn.

Top comments (0)