DApp Frontend Development
Overview
DApp frontend development bridges web technologies with blockchain, requiring understanding of wallet integration, transaction management, event listening, and decentralized storage.
âšī¸
DApp frontends differ from traditional web apps: they must handle wallet connections, manage blockchain state, and provide feedback on transaction confirmations.
Architecture Overview
React + Web3 Setup
Project Initialization
# Create React project with TypeScript
npx create-react-app my-dapp --template typescript
# Install Web3 dependencies
npm install ethers@6 wagmi viem @rainbow-me/rainbowkit
npm install @tanstack/react-query
# Install UI libraries
npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion
Provider Setup
// src/providers/Web3Provider.tsx
import { WagmiProvider, createConfig, http } from 'wagmi';
import { mainnet, polygon, arbitrum } from 'wagmi/chains';
import { RainbowKitProvider, getDefaultWallets } from '@rainbow-me/rainbowkit';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
const { connectors } = getDefaultWallets({
appName: 'My DApp',
projectId: 'YOUR_WALLETCONNECT_PROJECT_ID',
chains,
});
const config = createConfig({
chains: [mainnet, polygon, arbitrum],
connectors,
transports: {
[mainnet.id]: http(),
[polygon.id]: http(),
[arbitrum.id]: http(),
},
});
export function Web3Provider({ children }: { children: React.ReactNode }) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider coolMode>
{children}
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
);
}
Wallet Connection
Connect Button Component
// src/components/ConnectButton.tsx
import { ConnectButton as RainbowConnectButton } from '@rainbow-me/rainbowkit';
import { useAccount, useDisconnect, useBalance } from 'wagmi';
import { formatEther } from 'viem';
export function ConnectButton() {
const { address, isConnected, chain } = useAccount();
const { disconnect } = useDisconnect();
const { data: balance } = useBalance({ address });
if (isConnected) {
return (
<div className="wallet-info">
<div className="network-badge">
{chain?.name}
</div>
<div className="balance">
{balance ? `${parseFloat(formatEther(balance.value)).toFixed(4)} ETH` : 'Loading...'}
</div>
<div className="address">
{`${address?.slice(0, 6)}...${address?.slice(-4)}`}
</div>
<button onClick={() => disconnect()} className="disconnect-btn">
Disconnect
</button>
</div>
);
}
return <RainbowConnectButton />;
}
Wallet State Management
// src/hooks/useWalletState.ts
import { useAccount, useBalance, useChainId, useSwitchChain } from 'wagmi';
import { useState, useEffect } from 'react';
export function useWalletState() {
const { address, isConnected, connector } = useAccount();
const chainId = useChainId();
const { switchChain } = useSwitchChain();
const { data: balance, refetch: refetchBalance } = useBalance({ address });
const [isCorrectNetwork, setIsCorrectNetwork] = useState(true);
const requiredChainId = 1; // Mainnet
useEffect(() => {
setIsCorrectNetwork(chainId === requiredChainId);
}, [chainId, requiredChainId]);
const handleNetworkSwitch = async () => {
try {
await switchChain({ chainId: requiredChainId });
} catch (error) {
console.error('Failed to switch network:', error);
}
};
return {
address,
isConnected,
balance,
chainId,
isCorrectNetwork,
connector,
refetchBalance,
handleNetworkSwitch,
};
}
Transaction Handling
Transaction Manager Component
// src/components/TransactionManager.tsx
import { useState } from 'react';
import { useWriteContract, useWaitForTransactionReceipt } from 'wagmi';
import { parseEther } from 'viem';
const CONTRACT_ADDRESS = '0x...';
const CONTRACT_ABI = [
{
name: 'transfer',
type: 'function',
stateMutability: 'nonpayable',
inputs: [
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint256' },
],
outputs: [{ name: '', type: 'bool' }],
},
] as const;
export function TransactionManager() {
const [toAddress, setToAddress] = useState('');
const [amount, setAmount] = useState('');
const { writeContract, data: hash, isPending, error } = useWriteContract();
const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({
hash,
});
const handleTransfer = async () => {
if (!toAddress || !amount) return;
try {
writeContract({
address: CONTRACT_ADDRESS,
abi: CONTRACT_ABI,
functionName: 'transfer',
args: [toAddress as `0x${string}`, parseEther(amount)],
});
} catch (err) {
console.error('Transaction failed:', err);
}
};
return (
<div className="transaction-form">
<h3>Transfer ETH</h3>
<input
type="text"
placeholder="Recipient address"
value={toAddress}
onChange={(e) => setToAddress(e.target.value)}
className="input-field"
/>
<input
type="number"
placeholder="Amount (ETH)"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="input-field"
/>
<button
onClick={handleTransfer}
disabled={isPending || isConfirming}
className="submit-btn"
>
{isPending ? 'Confirming...' : isConfirming ? 'Pending...' : 'Transfer'}
</button>
{hash && (
<div className="tx-status">
<p>Transaction Hash: {hash}</p>
{isSuccess && <p className="success">Transaction Confirmed!</p>}
</div>
)}
{error && (
<div className="error">
Error: {error.message}
</div>
)}
</div>
);
}
Transaction Status Flow
Event Listening
Real-time Event Component
// src/components/EventListener.tsx
import { useEffect, useState } from 'react';
import { usePublicClient } from 'wagmi';
import { formatEther } from 'viem';
interface TransferEvent {
from: string;
to: string;
value: bigint;
blockNumber: bigint;
transactionHash: string;
}
export function EventListener() {
const [events, setEvents] = useState<TransferEvent[]>([]);
const publicClient = usePublicClient();
useEffect(() => {
if (!publicClient) return;
const unwatch = publicClient.watchContractEvent({
address: '0x...', // Contract address
abi: [
{
name: 'Transfer',
type: 'event',
inputs: [
{ name: 'from', type: 'address', indexed: true },
{ name: 'to', type: 'address', indexed: true },
{ name: 'value', type: 'uint256', indexed: false },
],
},
],
eventName: 'Transfer',
onLogs: (logs) => {
const newEvents = logs.map((log) => ({
from: log.args.from as string,
to: log.args.to as string,
value: log.args.value as bigint,
blockNumber: log.blockNumber,
transactionHash: log.transactionHash,
}));
setEvents((prev) => [...newEvents, ...prev].slice(0, 10));
},
onError: (error) => {
console.error('Event error:', error);
},
});
return () => unwatch();
}, [publicClient]);
return (
<div className="event-list">
<h3>Recent Transfers</h3>
<div className="events">
{events.map((event, index) => (
<div key={index} className="event-item">
<div className="event-hash">
TX: {event.transactionHash.slice(0, 10)}...
</div>
<div className="event-details">
From: {event.from.slice(0, 8)}... â To: {event.to.slice(0, 8)}...
</div>
<div className="event-value">
Amount: {formatEther(event.value)} ETH
</div>
<div className="event-block">
Block: {event.blockNumber.toString()}
</div>
</div>
))}
</div>
</div>
);
}
Event Polling vs WebSockets
| Method | Latency | Reliability | Cost |
|---|---|---|---|
| Polling | High | Medium | Low |
| WebSocket | Low | High | Medium |
| Hybrid | Medium | High | High |
IPFS Integration
IPFS Upload Component
// src/components/IPFSUpload.tsx
import { useState } from 'react';
import { create } from 'ipfs-http-client';
const projectId = 'YOUR_INFURA_PROJECT_ID';
const projectSecret = 'YOUR_INFURA_PROJECT_SECRET';
const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const client = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
export function IPFSUpload() {
const [file, setFile] = useState<File | null>(null);
const [ipfsHash, setIpfsHash] = useState('');
const [uploading, setUploading] = useState(false);
const uploadToIPFS = async () => {
if (!file) return;
setUploading(true);
try {
const result = await client.add(file);
setIpfsHash(result.path);
} catch (error) {
console.error('IPFS upload error:', error);
} finally {
setUploading(false);
}
};
return (
<div className="ipfs-upload">
<h3>Upload to IPFS</h3>
<input
type="file"
onChange={(e) => setFile(e.target.files?.[0] || null)}
className="file-input"
/>
<button
onClick={uploadToIPFS}
disabled={!file || uploading}
className="upload-btn"
>
{uploading ? 'Uploading...' : 'Upload to IPFS'}
</button>
{ipfsHash && (
<div className="ipfs-result">
<p>IPFS Hash: {ipfsHash}</p>
<a
href={`https://ipfs.io/ipfs/${ipfsHash}`}
target="_blank"
rel="noopener noreferrer"
>
View on IPFS
</a>
<p>For contract: ipfs://{ipfsHash}</p>
</div>
)}
</div>
);
}
IPFS Gateways
| Gateway | URL | Reliability |
|---|---|---|
| Infura | ipfs.infura.io | High |
| Pinata | api.pinata.cloud | High |
| Cloudflare | cloudflare-ipfs.com | High |
| Local | localhost:5001 | Development |
UI/UX Patterns
Loading States
// src/components/LoadingStates.tsx
import { useAccount, useBalance, useContractRead } from 'wagmi';
import { PulseLoader, ClipLoader } from 'react-spinners';
export function LoadingStates() {
const { isConnected, isConnecting, isReconnecting } = useAccount();
const { data: balance, isLoading: balanceLoading } = useBalance({
address: '0x...',
});
const { data: totalSupply, isLoading: contractLoading } = useContractRead({
address: '0x...',
abi: [...],
functionName: 'totalSupply',
});
// Wallet connection states
if (isConnecting) {
return <PulseLoader color="#3498db" />;
}
if (isReconnecting) {
return <ClipLoader color="#f39c12" />;
}
// Data loading states
if (balanceLoading || contractLoading) {
return (
<div className="skeleton-loading">
<div className="skeleton-line" />
<div className="skeleton-line short" />
</div>
);
}
return (
<div className="data-display">
<p>Balance: {balance?.formatted} ETH</p>
<p>Total Supply: {totalSupply?.toString()}</p>
</div>
);
}
Error Handling
// src/components/ErrorBoundary.tsx
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Uncaught error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="error-boundary">
<h2>Something went wrong</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
Responsive Design
Mobile-First DApp Layout
// src/components/DAppLayout.tsx
import { ConnectButton } from './ConnectButton';
import { useMediaQuery } from 'react-responsive';
export function DAppLayout({ children }: { children: React.ReactNode }) {
const isMobile = useMediaQuery({ maxWidth: 768 });
const isTablet = useMediaQuery({ minWidth: 769, maxWidth: 1024 });
return (
<div className={`dapp-layout ${isMobile ? 'mobile' : isTablet ? 'tablet' : 'desktop'}`}>
<header className="dapp-header">
<div className="logo">My DApp</div>
<ConnectButton />
</header>
<main className="dapp-main">
{children}
</main>
<footer className="dapp-footer">
<div className="network-info">
Network: Ethereum Mainnet
</div>
</footer>
</div>
);
}
Responsive CSS
/* src/styles/responsive.css */
.dapp-layout {
display: grid;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.dapp-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background: #1a1a2e;
color: white;
}
/* Mobile */
@media (max-width: 768px) {
.dapp-main {
padding: 0.5rem;
}
.wallet-info {
flex-direction: column;
gap: 0.5rem;
}
}
/* Tablet */
@media (min-width: 769px) and (max-width: 1024px) {
.dapp-main {
padding: 1rem;
}
}
/* Desktop */
@media (min-width: 1025px) {
.dapp-main {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
}
Real-World Example: Uniswap Interface
Key Features
| Feature | Implementation | Purpose |
|---|---|---|
| Wallet Connection | RainbowKit | Multi-wallet support |
| Network Switching | Wagmi | Multi-chain |
| Transaction Tracking | Custom hooks | UX feedback |
| Price Charts | TradingView | Data visualization |
| IPFS Deployment | Pinata | Decentralized hosting |
Performance Metrics
| Metric | Target | Actual |
|---|---|---|
| First Contentful Paint | < 1.5s | 1.2s |
| Largest Contentful Paint | < 2.5s | 2.1s |
| Time to Interactive | < 3.0s | 2.8s |
| Bundle Size | < 200KB | 180KB |
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Framework | React | Vue | React for Web3 ecosystem |
| State Management | Context | Zustand | Zustand for performance |
| Styling | CSS-in-JS | Tailwind | Tailwind for speed |
| RPC Provider | Public | Premium | Premium for reliability |
Interview Questions
-
How do you handle wallet connection state in a React DApp?
Use wagmi hooks like
useAccountto track connection state. Implement proper loading states for connecting/reconnecting. Handle network switching withuseSwitchChain. Provide clear UX feedback for all states. -
Explain the transaction lifecycle in a DApp and how to handle pending states.
Transactions go through: Pending (user signs) â Confirming (in mempool) â Confirmed (1 block) â Finalized (12+ blocks). Use
useWaitForTransactionReceiptto track status. Provide visual feedback and allow users to view on block explorer. -
How do you integrate IPFS for decentralized storage in a DApp?
Use ipfs-http-client to upload files. Store the returned CID in smart contracts or display to users. Provide IPFS gateway URLs for viewing. Consider pinning services for persistence.
Quiz Questions
-
What is the primary purpose of WalletConnect in a DApp?
- A) Store private keys
- B) Connect mobile wallets
- C) Manage network
- D) Deploy contracts
Answer: B - WalletConnect enables mobile wallet connection via QR code scanning.
-
Which hook is used to wait for transaction confirmation in wagmi?
- A) useTransaction
- B) useWaitForTransactionReceipt
- C) useSendTransaction
- D) useBlockNumber
Answer: B -
useWaitForTransactionReceiptpolls for transaction confirmation. -
What is the benefit of using IPFS for DApp frontend deployment?
- A) Faster loading
- B) Decentralized hosting
- C) Lower cost
- D) Better security
Answer: B - IPFS provides decentralized, censorship-resistant hosting for DApp frontends.