Building a DeFi Frontend: Libraries, Patterns, and Pitfalls
The libraries, data sources, and UX patterns for building DeFi frontends — wagmi, viem, The Graph, and how to handle real-time blockchain data.
DeFi frontends have to handle real-time blockchain data, wallet state, pending transactions, and complex state management — all while providing a UI that doesn't require users to understand gas. This guide covers the standard stack.
The Core Stack
viem: the modern TypeScript library for Ethereum interactions. Type-safe, fast, tree-shakable. Replaces ethers.js for most new projects. wagmi: React hooks built on top of viem. Handles wallet connection, contract reads/writes, network state. The combination of wagmi + viem is now the standard for EVM dApp frontends.
Reading Contract State
wagmi's useReadContract hook handles reading state from contracts. For data that updates frequently (prices, balances), use refetchInterval to poll. For one-off reads, fetch on component mount. For data that only changes on specific events, combine a readContract with a useWatchContractEvent listener that triggers a refetch. Cache aggressively where data doesn't change often.
Writing to Contracts (Transactions)
wagmi's useWriteContract hook manages the full transaction lifecycle: gas estimation, sending to the wallet, waiting for confirmation. Always handle the pending state in the UI — show a spinner and disable the button after submission. Listen for receipt confirmation (useWaitForTransactionReceipt) before showing success state. Display the transaction hash with an Etherscan link immediately on submission.
Real-Time Data
For real-time prices, use Chainlink or Pyth's SDK for price feeds, or The Graph for protocol-specific data. WebSocket RPC endpoints (Alchemy, Infura) allow subscribing to events in real-time. For high-frequency updates, Pyth's Hermes API provides sub-second price updates. For historical data (charts, position history), The Graph is standard.
Transaction UX Patterns
Optimistic updates: update UI immediately on submission, revert if transaction fails. Transaction queue: let users submit multiple transactions and track them together. Gas estimation display: show estimated gas cost before submission in fiat terms. MEV protection toggle: let power users choose between fast (public mempool) and protected (Flashbots) submission.
Mobile Considerations
Mobile browsers require WalletConnect for wallet connection (MetaMask mobile, Coinbase Wallet). Test every user flow on mobile — many DeFi UX issues only appear on mobile. Consider Privy or Dynamic for email/social login to remove the 'install a wallet' requirement. TailwindCSS + responsive design is essential — significant DeFi traffic is mobile.
Related Guides
Ready to build your Web3 project?
Tell us about your project and get a precise quote.
Get a Project Quote