web3-react
A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
Top Related Projects
Complete Ethereum library and wallet implementation in JavaScript.
:globe_with_meridians: :electric_plug: The MetaMask browser extension enables browsing Ethereum blockchain enabled websites
WalletConnect Monorepo
Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
Quick Overview
Web3-react is a simple, maximally extensible React framework for building single-page Ethereum dApps. It provides a set of hooks and components to easily connect to Ethereum wallets and interact with the blockchain, making it easier for developers to create decentralized applications.
Pros
- Modular architecture with support for multiple connectors (MetaMask, WalletConnect, etc.)
- Easy integration with React applications
- Comprehensive documentation and examples
- Active community and regular updates
Cons
- Learning curve for developers new to Web3 development
- Dependency on external wallet providers
- Limited built-in UI components, requiring additional styling
- Potential compatibility issues with older React versions
Code Examples
- Connecting to a wallet:
import { useWeb3React } from '@web3-react/core'
import { InjectedConnector } from '@web3-react/injected-connector'
const injected = new InjectedConnector({ supportedChainIds: [1, 3, 4, 5, 42] })
function ConnectWallet() {
const { activate } = useWeb3React()
return <button onClick={() => activate(injected)}>Connect to MetaMask</button>
}
- Fetching account balance:
import { useWeb3React } from '@web3-react/core'
import { formatEther } from '@ethersproject/units'
function AccountBalance() {
const { account, library } = useWeb3React()
const [balance, setBalance] = useState()
useEffect(() => {
if (account) {
library.getBalance(account).then((balance) => {
setBalance(formatEther(balance))
})
}
}, [account, library])
return <div>Balance: {balance} ETH</div>
}
- Interacting with a smart contract:
import { useWeb3React } from '@web3-react/core'
import { Contract } from '@ethersproject/contracts'
const contractABI = [/* ... */]
const contractAddress = '0x...'
function InteractWithContract() {
const { library, account } = useWeb3React()
const contract = new Contract(contractAddress, contractABI, library.getSigner())
const handleInteraction = async () => {
try {
const tx = await contract.someFunction()
await tx.wait()
console.log('Transaction successful')
} catch (error) {
console.error('Error:', error)
}
}
return <button onClick={handleInteraction}>Interact with Contract</button>
}
Getting Started
- Install the required packages:
npm install @web3-react/core @web3-react/injected-connector ethers
- Set up the Web3ReactProvider in your app:
import { Web3ReactProvider } from '@web3-react/core'
import { Web3Provider } from '@ethersproject/providers'
function getLibrary(provider) {
return new Web3Provider(provider)
}
function App() {
return (
<Web3ReactProvider getLibrary={getLibrary}>
{/* Your app components */}
</Web3ReactProvider>
)
}
- Use the
useWeb3React
hook in your components to access Web3 functionality.
Competitor Comparisons
Complete Ethereum library and wallet implementation in JavaScript.
Pros of ethers.js
- More comprehensive and feature-rich library for Ethereum interactions
- Better documentation and wider community support
- Supports both browser and Node.js environments
Cons of ethers.js
- Steeper learning curve due to its extensive feature set
- May be overkill for simple dApp projects
- Requires more setup and configuration
Code Comparison
ethers.js:
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(address, abi, signer);
const tx = await contract.someFunction();
await tx.wait();
web3-react:
const { account, library } = useWeb3React();
const contract = new library.eth.Contract(abi, address);
const tx = await contract.methods.someFunction().send({ from: account });
await tx.wait();
Summary
ethers.js is a more comprehensive Ethereum library with extensive features and better documentation. It's suitable for complex projects but may be overwhelming for simpler dApps. web3-react, on the other hand, is more focused on React integration and easier to use for basic web3 functionality. The choice between the two depends on the project's requirements and the developer's familiarity with Ethereum development.
:globe_with_meridians: :electric_plug: The MetaMask browser extension enables browsing Ethereum blockchain enabled websites
Pros of metamask-extension
- Widely adopted and trusted browser extension for Ethereum interactions
- Comprehensive wallet functionality including token management and transaction signing
- Extensive documentation and community support
Cons of metamask-extension
- Larger codebase and more complex architecture
- Focused primarily on wallet functionality, less flexible for custom dApp integrations
- Steeper learning curve for developers new to Ethereum development
Code Comparison
metamask-extension:
const provider = new MetaMaskInpageProvider(connectionStream, {
shouldSendMetadata: true,
shouldSetOnWindow: true,
});
web3-react:
import { InjectedConnector } from '@web3-react/injected-connector'
const injected = new InjectedConnector({ supportedChainIds: [1, 3, 4, 5, 42] })
metamask-extension provides a more comprehensive solution for Ethereum wallet integration, while web3-react offers a more flexible and lightweight approach for connecting dApps to various Web3 providers. web3-react is better suited for developers who need a simple way to connect their dApps to multiple wallet providers, while metamask-extension is ideal for those who want to leverage MetaMask's full feature set and widespread adoption.
WalletConnect Monorepo
Pros of walletconnect-monorepo
- Broader support for various wallet types and platforms
- More comprehensive documentation and examples
- Active development and frequent updates
Cons of walletconnect-monorepo
- Larger codebase and potentially more complex integration
- May include unnecessary features for simpler projects
- Steeper learning curve for developers new to Web3
Code Comparison
walletconnect-monorepo:
import WalletConnect from "@walletconnect/client";
import QRCodeModal from "@walletconnect/qrcode-modal";
const connector = new WalletConnect({
bridge: "https://bridge.walletconnect.org",
qrcodeModal: QRCodeModal,
});
web3-react:
import { InjectedConnector } from '@web3-react/injected-connector'
import { useWeb3React } from '@web3-react/core'
const injected = new InjectedConnector({ supportedChainIds: [1, 3, 4, 5, 42] })
const { activate } = useWeb3React()
The walletconnect-monorepo code showcases its focus on QR code-based connections and broader wallet support, while web3-react demonstrates a more straightforward approach for injected wallets like MetaMask. web3-react's code is generally simpler, but may lack some advanced features offered by walletconnect-monorepo.
Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
Pros of web3.js
- More comprehensive and established library for Ethereum interactions
- Supports a wider range of Ethereum-related functionalities
- Larger community and more extensive documentation
Cons of web3.js
- Heavier and more complex, which may lead to larger bundle sizes
- Less focused on React integration compared to web3-react
- May require more setup and configuration for React projects
Code Comparison
web3.js:
import Web3 from 'web3';
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546');
const balance = await web3.eth.getBalance(address);
web3-react:
import { useWeb3React } from '@web3-react/core';
const { account, library } = useWeb3React();
const balance = await library.eth.getBalance(account);
Summary
web3.js is a more comprehensive Ethereum library with broader functionality, while web3-react is specifically designed for React integration. web3.js offers more features but may be more complex to set up in React projects. web3-react provides a simpler, React-focused approach but with potentially fewer overall features. The choice between them depends on the specific needs of your project and your familiarity with React development.
A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
Pros of web3-react
- More actively maintained with regular updates
- Broader community support and adoption
- Extensive documentation and examples
Cons of web3-react
- Steeper learning curve for beginners
- Larger bundle size due to additional features
- May require more configuration for simple use cases
Code Comparison
web3-react:
import { Web3ReactProvider } from '@web3-react/core'
import { Web3Provider } from '@ethersproject/providers'
function getLibrary(provider) {
return new Web3Provider(provider)
}
web3-react:
import { Web3ReactProvider } from '@web3-react/core'
import { Web3Provider } from '@ethersproject/providers'
function getLibrary(provider) {
return new Web3Provider(provider)
}
Both repositories share similar core functionality for integrating Web3 into React applications. The main differences lie in the implementation details, community support, and maintenance frequency. web3-react tends to have more frequent updates and a larger user base, while web3-react may be simpler for basic use cases but with potentially less robust features.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
web3-react (beta)
Looking for the prior version of this library? It's available on the v6 branch.
Example
This is a hosted version of example.
Packages
Get Started
yarn
yarn start
In addition to compiling each package in watch mode, this will also spin up /example on localhost:3000.
Run Tests
yarn build
yarn test --watch
Publish
yarn lerna publish [--dist-tag]
Documentation
This version of web3-react is still in beta, so unfortunately documentation is pretty sparse at the moment. /example, TSDoc comments, and the source code itself are the best ways to get an idea of what's going on. More thorough documentation is a priority as development continues!
Upgrading Connector Dependencies
Some connectors have one or more dependencies that are specific to the connection method in question. For example, the walletconnect connector relies on @walletconnect/ethereum-provider
package to handle a lot of the connection logic. Often, you may wish to upgrade to the latest version of a client package, to take advantage of the latest features. web3-react makes the process of upgrading client packages fairly painless by specifying them as peerDependencies
. This means that you have to explicitly install client packages, and therefore may transparently switch between any version that agrees with the semver specified in the connector (usually any matching major).
Third-Party Connectors
The decision to publish a connector under the @web3-react namespace is fully up to the discretion of the team. However, third-party connectors are always welcome! This library was designed to be highly modular, and you should be able to draw inspiration from the existing connectors to write your own. That connector can live inside your codebase, or even be published as a standalone package. A selection of third-party connectors that have widespread usage may be featured below, PRs modifying this list are welcome.
Upgrading from v6
While the internals of web3-react have changed fairly dramatically between v6 and v8, the hope is that usage don't have to change too much when upgrading. Once you've migrated to the new connectors and state management patterns, you should be able to use the hooks defined in @web3-react/core, in particular useWeb3React
(or usePriorityWeb3React
), as more or less drop-in replacements for the v6 hooks. The big benefit in v8 is that hooks are now per-connector, as opposed to global, so no more juggling between connectors/multiple roots!
Top Related Projects
Complete Ethereum library and wallet implementation in JavaScript.
:globe_with_meridians: :electric_plug: The MetaMask browser extension enables browsing Ethereum blockchain enabled websites
WalletConnect Monorepo
Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot