Overview
TheuseWallet hook provides complete wallet management for Stacks blockchain authentication. It handles connecting/disconnecting wallets, managing user sessions, and formatting addresses for display.
Source: src/hooks/useWallet.js
Import
Hook Signature
Configuration
The hook uses theNetworkContext to determine whether to use mainnet or testnet addresses:
Return Values
Whether a wallet is currently connected.
true if user is authenticated, false otherwise.The user’s Stacks address for the active network. Returns the testnet address if
network === 'testnet', otherwise returns mainnet address. null if not connected.true while authentication popup is active, false otherwise. Useful for disabling UI elements during connection.Utility function to format addresses for display.Signature:
(addr: string) => stringExample: "SP2H8...7SA5" (first 5 + last 4 characters)Opens the Stacks wallet authentication popup. Handles the complete authentication flow including:
- Launching wallet selector (Leather, Xverse, etc.)
- Processing authentication callback
- Extracting address for current network
- Updating connection state
() => voidSigns out the current user, clears session data, and reloads the page to reset application state.Signature:
() => voidUsage Example
Authentication Flow
The hook implements the standard Stacks authentication flow:Wallet popup appears
User selects their Stacks wallet (Leather, Xverse, etc.) and approves connection
Authentication callback
Hook receives user session data and extracts the appropriate address (mainnet or testnet)
Network Handling
The hook automatically selects the correct address based on your network configuration:Make sure your
NetworkContext is properly configured in your app’s root component to ensure the correct network addresses are used.App Configuration
The hook uses these app details for wallet authentication:Session Persistence
On component mount, the hook checks for existing sessions:Best Practices
Loading States
Always check
loading state to disable buttons and prevent double-clicks during authenticationConditional Rendering
Use
connected to show/hide wallet-dependent features and protect sensitive routesAddress Display
Always use
shortAddress() for displaying addresses in UI to improve readabilityError Handling
The hook handles errors internally, but you can add try-catch in
connectWallet if neededCommon Patterns
Conditional Feature Access
Multiple Hook Composition
Related Hooks
- usePortfolio - Fetch wallet portfolio data
- useAIAdvisor - Generate AI strategies
- useProtocols - Browse DeFi protocols
Related Services
- Authentication - Stacks Connect authentication details
- Stacks API - Blockchain data fetching