
Lesson 5: Frontend Integration — React and Wagmi
Learning goals: connect a wallet, read a contract, and send a tipping transaction.
Previous lesson
Lesson outline
1. A brief introduction to Wagmi
2. Why choose Wagmi?
3. Installation and configuration
4. A hands-on project: a Web3 tip jar
5. Assembly and testing
6. Common problems and best practices
1. A brief introduction to Wagmi
Wagmi is a Web3 frontend toolkit built on React Hooks. If Viem is the underlying engine for talking to the blockchain (similar to fetch or axios in Web2), then Wagmi is a business-layer wrapper tailored for React (similar to SWR or React Query).
Main features
Ready to use: it comes with dozens of commonly used React Hooks (connecting a wallet, checking a balance, calling a contract, and so on).
Native caching: the underlying layer is driven by @tanstack/react-query, which automatically handles request deduplication, caching, and polling.
Type safety: deep TypeScript integration, with strong type inference at the ABI level.
A minimal architecture: say goodbye to the cumbersome Provider state management of the Web3.js / Ethers.js era.
2. Why choose Wagmi?
For Web2 developers, the most painful part of handling blockchain interaction is state synchronization. Blockchain data are asynchronous and require waiting for block confirmation.
2.1 A comparison of core advantages

3. Installation and configuration
We will use Vite to quickly scaffold a modern React project.
3.1 Initializing the project
3.2 Installing the core dependencies
Install Wagmi, Viem, and React Query:
3.3 Configuring a global Provider
In the src directory, create config.ts and configure the supported blockchain networks (here we use Ethereum mainnet and the Sepolia testnet as examples):
Modify src/main.tsx and wrap your application with the Provider:
4. A hands-on project: a Web3 tip jar
Our project is divided into three core steps: connect an identity, display data, and send a tip.
4.1 Step 1: connect the user's wallet (Login)
In Web3, connecting a wallet is logging in. We create a WalletConnect.tsx component.
4.2 Step 2: read on-chain data (Read)
After the user connects, we want to display their ETH balance and try to resolve their ENS name (similar to fetching a user profile in Web2).
4.3 Step 3: send a tipping transaction (Write / Transaction)
This is the most exciting step. We will call useSendTransaction to send ETH to a specified address, and handle the waiting state of the transaction.
5. Assembly and testing
Assemble all the components into App.tsx:
5.1 Running and debugging locally
Run npm run dev. Make sure your MetaMask is switched to the Sepolia testnet and that you have some test ETH (you can claim it from a faucet). You can try tipping yourself and watch the button state change smoothly from “Confirm in wallet” to “Included in a block” and then to “Tip sent successfully”.
6. Common problems and best practices
6.1 Handling large numbers (BigInt)
A common mistake among Web2 developers is to use an ordinary Number to handle amounts. Ethereum has 18 digits of precision, which can easily cause JS precision loss.
Best practice: always use parseEther (on input) and formatEther (on display) as provided by Viem, and keep the BigInt type in the underlying logic.
6.2 Error handling
Users may tap “Reject” in the wallet popup at any time.
Best practice: catch UserRejectedRequestError in the onError callback of sendTransaction, and give the user a friendly toast, rather than letting the console throw an error.
6.3 Bringing in a component library (RainbowKit)
In a real production environment, we usually do not hand-write a basic connect button.
Best practice: use RainbowKit or Web3Modal. Under the hood they are fully based on Wagmi, but they give you a polished multi-wallet UI (supporting QR codes, mobile deep links, and more).
Code snippets from the article
The following code comes from code blocks in the original X Article, arranged in the order they appeared.
// src/App.tsx
import { WalletConnect } from './components/WalletConnect'
import { UserProfile } from './components/UserProfile'
import { TipJar } from './components/TipJar'
import { useAccount } from 'wagmi'
function App() {
const { isConnected } = useAccount()
return (
<div style={{ maxWidth: '500px', margin: '50px auto', fontFamily: 'sans-serif' }}>
<h1>💎 Web3 Tip Jar</h1>
<WalletConnect />
{isConnected && (
<>
<UserProfile />
<TipJar />
</>
)}
</div>
)
}
export default App
// src/components/WalletConnect.tsx
import { useAccount, useConnect, useDisconnect } from 'wagmi'
import { injected } from 'wagmi/connectors'
export function WalletConnect() {
const { address, isConnected } = useAccount()
const { connect } = useConnect()
const { disconnect } = useDisconnect()
if (isConnected) {
return (
<div>
<p>Connected: {address?.slice(0, 6)}...{address?.slice(-4)}</p>
<button onClick={() => disconnect()}>Disconnect</button>
</div>
)
}
return (
<button onClick={() => connect({ connector: injected() })}>
Connect MetaMask
</button>
)
}
npm install wagmi viem @tanstack/react-query
// src/components/UserProfile.tsx
import { useAccount, useBalance, useEnsName } from 'wagmi'
export function UserProfile() {
const { address } = useAccount()
// Read the balance
const { data: balance } = useBalance({ address })
// Read the ENS name (for example, alice.eth)
const { data: ensName } = useEnsName({ address })
if (!address) return null
return (
<div style={{ padding: '20px', border: '1px solid #ccc', marginTop: '20px' }}>
<h3>👋 Welcome, {ensName ? ensName : 'mysterious hacker'}</h3>
<p>Your wallet balance: {balance?.formatted} {balance?.symbol}</p>
</div>
)
}
// src/config.ts
import { http, createConfig } from 'wagmi'
import { mainnet, sepolia } from 'wagmi/chains'
export const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
})
// src/components/TipJar.tsx
import { useState } from 'react'
import { useSendTransaction, useWaitForTransactionReceipt } from 'wagmi'
import { parseEther } from 'viem'
export function TipJar() {
const [amount, setAmount] = useState('0.01')
// Recipient address (you can replace this with your own address)
const RECEIVER_ADDRESS = '0xYourAddressHere...'
const { data: hash, sendTransaction, isPending } = useSendTransaction()
// Watch the on-chain status of the transaction
const { isLoading: isConfirming, isSuccess: isConfirmed } =
useWaitForTransactionReceipt({ hash })
const handleTip = () => {
sendTransaction({
to: RECEIVER_ADDRESS,
value: parseEther(amount), // Convert 0.01 into Wei
})
}
return (
<div style={{ marginTop: '20px', padding: '20px', background: '#f5f5f5' }}>
<h3>☕ Buy me a coffee</h3>
<input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
step="0.01"
/> ETH
<button
onClick={handleTip}
disabled={isPending || isConfirming}
style={{ marginLeft: '10px' }}
>
{isPending ? 'Confirm in wallet...' : isConfirming ? 'Included in a block...' : 'Tip'}
</button>
{/* Status feedback */}
{hash && <p style={{ fontSize: '12px' }}>Transaction hash: {hash}</p>}
{isConfirmed && <p style={{ color: 'green' }}>🎉 Tip sent successfully! Thank you so much!</p>}
</div>
)
}
// src/main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { WagmiProvider } from 'wagmi'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { config } from './config'
import App from './App'
const queryClient = new QueryClient()
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</WagmiProvider>
</React.StrictMode>,
)
npm create vite@latest web3-tip-jar -- --template react-ts
cd web3-tip-jar
npm install
This article was imported from an X Article. Original: https://x.com/i/status/2110719203603095639