DApp Frontend (wagmi + React) — Web3

wagmi 3 is React hooks on top of viem and TanStack Query. Set up createConfig with chains: [hardhat, sepolia], the injected() connector (EIP-6963 wallets are…

So far every call to a contract has been a Node script that runs once and ends. A React page is a different story. Its button has to know when the wallet popup is open and when it's still waiting for a block, and the PTS figure has to change once the transaction is in. That's where wagmi comes in: a React hooks library for Ethereum, built on viem (the ethers.js / viem lesson) and TanStack Query. Wallet connections, contract reads and sent transactions become React state that updates by itself, complete with loading, error and success statuses. Think of wagmi as Raka's Shirt Shop's front-desk clerk. You just say "show Dinda's PTS" or "redeem 100 PTS". The clerk asks the warehouse (the node), remembers the answer so they don't keep walking back (the cache), hands the form to the customer's wallet to sign, then tells you when the transaction is in a block.

Versions and a note about this page

This lesson uses wagmi 3.7.7 (major 3; the latest as of 15 November 2026: 3.7.11) with viem 2.57.4 and @tanstack/react-query 5. In wagmi 3 a few names changed: useAccount is now useConnection, the wallet list comes from useConnectors(), and the send function of useWriteContract and useConnect is called mutate. The old names still exist but are marked deprecated. The BelajarWeb.dev site itself doesn't install wagmi, so the code below was run in a separate project: React 19 and wagmi 3.7.7 inside happy-dom, against a local Hardhat node, with a mock wallet. Every output in this lesson comes from there. The Lab on this page runs a hand-written version of the same flow.

Config: chains, connectors, transports

npm install wagmi@3 viem@2 @tanstack/react-query
// config.js
import { createConfig, http } from 'wagmi'
import { hardhat, sepolia } from 'wagmi/chains'
import { injected } from 'wagmi/connectors'

export const config = createConfig({
  chains: [hardhat, sepolia],
  connectors: [injected()],
  transports: {
    [hardhat.id]: http(),
    [sepolia.id]: http(),
  },
})
// App.jsx
import { WagmiProvider } from 'wagmi'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { config } from './config'
import { MyPoints } from './MyPoints'

const queryClient = new QueryClient()

export function App() {
  return (
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        <MyPoints />
      </QueryClientProvider>
    </WagmiProvider>
  )
}

These two providers must wrap every component that uses wagmi hooks. The QueryClient is TanStack Query's cache, where every read result is kept.

The component: reading PTS and redeeming

// MyPoints.jsx
import { useEffect } from 'react'
import { useConnection, useConnectors, useConnect, useReadContract, useWriteContract, useWaitForTransactionReceipt } from 'wagmi'
import { formatUnits, parseAbi, parseUnits } from 'viem'

const PTS = '0x5FbDB2315678afecb367f032d93F642f64180aa3'
const abi = parseAbi([
  'function balanceOf(address account) view returns (uint256)',
  'function redeem(uint256 amount)',
  'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
])

export function MyPoints() {
  const { address, status } = useConnection()
  const connectors = useConnectors()
  const connect = useConnect()
  const balance = useReadContract({
    address: PTS,
    abi,
    functionName: 'balanceOf',
    args: address ? [address] : undefined,
    query: { enabled: Boolean(address) },
  })
  const redeem = useWriteContract()
  const receipt = useWaitForTransactionReceipt({ hash: redeem.data })

  const { refetch } = balance
  useEffect(() => {
    if (receipt.isSuccess) refetch()
  }, [receipt.isSuccess, refetch])

  if (status !== 'connected') {
    return connectors.map((connector) => (
      <button key={connector.uid} onClick={() => connect.mutate({ connector })}>
        Connect {connector.name}
      </button>
    ))
  }

  return (
    <div>
      <p>Your PTS: {balance.data === undefined ? '...' : formatUnits(balance.data, 18)}</p>
      <button
        disabled={redeem.isPending || receipt.isLoading}
        onClick={() => redeem.mutate({ address: PTS, abi, functionName: 'redeem', args: [parseUnits('100', 18)] })}
      >
        {redeem.isPending ? 'Confirm in your wallet...' : receipt.isLoading ? 'Waiting for a block...' : 'Redeem 100 PTS'}
      </button>
      {receipt.isSuccess && <p>Done in block {String(receipt.data.blockNumber)}</p>}
      {redeem.error && <p>{redeem.error.shortMessage ?? redeem.error.message}</p>}
    </div>
  )
}

What happens when it runs

This is the page's content from a real render, RakaPoints's ERC-20 version on the local chain (Dinda has 160 PTS), step by step:

Step Text on the page Behind the scenes
first render Connect Injected Connect Mock Wallet injected() plus the wallet found through EIP-6963
click Connect Mock Wallet Your PTS: ... status becomes 'connected'; the balanceOf query is pending and fetching
Your PTS: 160 the query is success, the node answered the eth_call
click Redeem Confirm in your wallet... redeem.isPending: the wallet popup is open
the wallet approves Waiting for a block... there's a hash; receipt is fetching
Your PTS: 160 Done in block 6 the receipt is success, but the cache still holds 160
Your PTS: 60 refetch reads balanceOf again

Look at the line "Done in block 6" next to "Your PTS: 160". Did the transaction fail? No: it succeeded, but useReadContract shows the old answer from the cache until it's read again. TanStack Query keeps it under this key:

["readContract",{"address":"0x5FbDB2315678afecb367f032d93F642f64180aa3","functionName":"balanceOf","args":["0x70997970C51812dc3A010C7d01b50e0d17dc79C8"],"chainId":31337}]

Any other component asking for Dinda's balanceOf with the same key gets the same answer straight from the cache, and when both ask at the same time, only one eth_call goes out.

Loading, error and success

State Written as Show
a read running balance.status === 'pending' or balance.fetchStatus === 'fetching' ...
waiting for a signature redeem.isPending "Confirm in your wallet..."
waiting for a block receipt.isLoading "Waiting for a block..."
success receipt.isSuccess the block number, then read the balance again
failure redeem.error error.shortMessage

Two errors showed up in that render. Dinda pressed Reject in her wallet: User rejected the request. Dinda pressed Redeem again with 60 PTS left, and redeem.error.message held:

The contract function "redeem" reverted.

Error: ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)
                               (0x70997970C51812dc3A010C7d01b50e0d17dc79C8, 60000000000000000000, 100000000000000000000)

Its first line is the shortMessage. Because error ERC20InsufficientBalance is in the abi, viem can name it. The button is also disabled while waiting, so it can't be sent twice.

⚠️ Statuses and hook names that are easy to misuse

TL;DR: wagmi 3 is React hooks on top of viem and TanStack Query. Set up createConfig with chains: [hardhat, sepolia], the injected() connector (EIP-6963 wallets are found automatically) and transports, then wrap the app in WagmiProvider and QueryClientProvider. useConnection gives the address and status, useConnectors plus useConnect().mutate connect a wallet, useReadContract reads balanceOf through the cache (key ['readContract', {...}]), useWriteContract().mutate sends redeem, and useWaitForTransactionReceipt waits for the block. Once the receipt is success, call refetch, or the screen still says 160. Show isPending, isLoading, isSuccess and error.shortMessage so the user knows what's going on.

⚡ wagmi: React hooks on top of viem

Meaning: wagmi turns wallet connections, contract reads and transactions into React state that updates by itself, complete with loading, error and success statuses. Wrap the app in WagmiProvider and QueryClientProvider.

⚡ Reading: useReadContract

Write:

const balance = useReadContract({
  address: PTS,
  abi,
  functionName: 'balanceOf',
  args: address ? [address] : undefined,
  query: { enabled: Boolean(address) },
})

Meaning: This is viem's readContract wrapped in useQuery. query: { enabled } holds it back until there's an address.

⚡ Writing: useWriteContract, then wait for the block

Write:

const redeem = useWriteContract()
const receipt = useWaitForTransactionReceipt({ hash: redeem.data })

Meaning: redeem.mutate(...) opens the wallet popup, and redeem.data is the hash. What confirms the transaction is in a block is useWaitForTransactionReceipt.

⚡ The cache still holds the old number

Guess first: the page shows "Done in block 6" next to "Your PTS: 160", though Dinda just redeemed 100. Did the transaction fail?

No. It succeeded, but useReadContract shows the old answer from the cache until it's read again.

Meaning: Call refetch once on receipt.isSuccess, and the screen moves to 60.

What you will learn