Track 6 · dApps & frontend · lesson 3
Connect wallet
12 min
viem talks to a chain. wagmi wraps viem in React hooks and handles the messy parts of wallets: connecting, disconnecting, network switching, and re-rendering when any of it changes.
You could do all of this with viem alone. wagmi exists because wallet state is annoying in a UI: the user can switch accounts, change networks, or disconnect at any moment, from outside your app, and every one of those has to flow back into your components. wagmi turns that into hooks that just update.
Connecting
import { useAccount, useConnect, useDisconnect } from "wagmi";
function ConnectButton() {
const { address, isConnected } = useAccount();
const { connect, connectors } = useConnect();
const { disconnect } = useDisconnect();
if (isConnected) {
return <button onClick={() => disconnect()}>{address}</button>;
}
return (
<button onClick={() => connect({ connector: connectors[0] })}>
Connect wallet
</button>
);
}
useAccount is the hook you will reach for most: it tells you who is connected,
and re-renders when that changes.
What connecting is, once more
From track 2, made concrete: connect triggers the wallet's popup. The user
approves, and your app learns their address. That is the entire exchange. No
key crosses the boundary, and your app gains no power to move anything — only to
ask.
Predict
A user connects, then switches to a different account inside MetaMask without touching your app. What should happen?
Config, briefly
wagmi needs a one-time setup naming the chains and connectors your app supports, wrapped around your React tree. In practice most projects use RainbowKit or ConnectKit on top, which provide a polished connect-wallet modal so you do not build one by hand.
Check
What does `connect` actually obtain from the user?
Worth remembering
- wagmi wraps viem in React hooks and manages wallet, account and network state.
- `useAccount` reports who is connected and re-renders on change.
- Connecting shares only the address; the key stays in the wallet.
- Your app must react to account and network switches, or it acts on stale state.
- RainbowKit/ConnectKit provide the connect modal so you don't build one.