Web3 React
Web3 React is a drop in solution for building single-page Ethereum dApps in React. Yes, it uses Hooks!
The marquee features of Web3 React are:
-
A robust management framework for the web3
object injected into browsers by MetaMask, Trust, etc. The framework exposes the current account, the current network ID, and an instantiated web3.js instance via a React Context.
-
A collection of React Hooks that can be used to display ETH and ERC20 balances, sign messages, and more.
-
A number of utility functions that format Etherscan links, convert token balances, and more.
-
A complete solution for sending transactions that abstracts away from common annoyances like estimating gas usage, setting a gas price, and checking for transaction errors.
Sample Implementations
Many of the patterns and APIs described below are shown in this CodeSandbox demo:
Open a PR to include your Web3 React project here!
Quickstart
Install the npm package:
npm install web3-react
Web3 React exports 4 objects:
Web3Provider
(default export)
- A Component wrapping a React Context Provider that ensure children can access the
Web3Context
. Web3Provider
takes 4 optional props.
Web3Context
(named export)
- A React Context object that consists of 4 elements.
Web3Consumer
(named export)
- A Component wrapping a React Context Consumer that enables children to access the
Web3Context
via a render prop. Web3Consumer
takes 2 optional props.
withWeb3
(named export)
- This HOC gives passed Components access to the
Web3Context
via an injected web3
prop. withWeb3
takes 1 optional argument.
Using Web3 React: Starter Code
To take advantage of the Web3Context
, Components must have a Web3Provider
parent somewhere in their tree. It's recommended that the Web3Provider
be placed at the top level of your app.
import React from 'react'
import ReactDOM from 'react-dom'
import Web3Provider from 'web3-react'
function App () {
return (
<Web3Provider>
...
</Web3Provider>
)
}
const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)
Using Web3 React: Hooks - Recommended
The easiest way to use Web3 React is with Hooks! All Hooks exported by Web3 React are documented in docs/Hooks.md.
import React, { useContext } from 'react'
import { Web3Context } from 'web3-react'
import { useAccountBalance } from 'web3-react/hooks'
function MyComponent () {
const context = useContext(Web3Context)
const balance = useAccountBalance()
return (
<>
<p>{context.account}</p>
<p>{balance}</p>
</>
)
}
Using Web3 React: Render Props - Conditionally Recommended
To access the Web3Context
with a render prop, wrap Components in a Web3Consumer
.
import React from 'react'
import Web3Provider, { Web3Consumer } from 'web3-react'
function AccountComponent (props) {
const { account } = props
return <p>{account}</p>
}
function MyComponent () {
return (
<Web3Consumer>
{context =>
<AccountComponent account={context.account} />
}
</Web3Consumer>
)
}
Note: This pattern will work for arbitrarily deeply nested components. This means that the Web3Consumer
doesn't necessarily need to be at the top level of your app. There also won't be performance concerns if you choose to use multiple Web3Consumer
s at different nesting levels.
Using Web3 React: HOCs - Not Recommended
If you really have to, you can give Components access to the Web3Context
via a web3
prop by wrapping them with withWeb3
.
import React from 'react'
import { withWeb3 } from 'web3-react'
function MyComponent (props) {
const { web3 } = props
const { account } = web3
return <p>{account}</p>
}
const MyComponentWrapped = withWeb3(MyComponent)
Note: The high-level component which includes your Web3Provider
Component cannot be wrapped with withWeb3
.
Exhaustive Documentation
-
Documentation for the utility functions exported by Web3 React can be found separately in docs/Utilities.md.
-
Documentation for the Hooks exported by Web3 React can be found separately in docs/Hooks.md.
1. Web3Provider
props
The Web3Provider
Component takes 4 optional props:
screens
: React Components which will be displayed according to the web3 status of a user's browser. To see the default screens, play around with the CodeSandbox sample app or check out the implementation.
-
Initializing
: Shown when Web3 React is being initialized. This screen is typically displayed only very briefly, or while requesting one-time account permission.
- Default: The Component only appears after 1 second.
-
NoWeb3
: Shown when no injected web3
variable is found.
- Default: The Component encourages users to install MetaMask or download Trust.
-
PermissionNeeded
: Shown when users deny your dApp permission to access their account. Right now, denying access disables the entire dApp. If this is an issue for your use case (i.e. if your dApp supports generic, read-only experiences) please file an issue or submit a PR.
- Default: The Component instructs users to grant your dApp access to their account.
-
UnlockNeeded
: Shown when no account is available.
- Default: The Component encourages users to unlock their wallet. This could possibly be combined with the
PermissionNeeded
Component (suggestions welcome).
-
UnsupportedNetwork
: Shown when the user is on a network not in the supportedNetworks
list. The list of supported network IDs is passed to this component in a supportedNetworkIds
prop.
- Default value: The Component encourages users to connect to any of the networks in the
supportedNetworks
list.
-
Web3Error
: Shown whenever an error occurs in the polling process for account and network changes. The error is passed to this Component as an error
prop.
- Default: The Component displays the text of the passed error to the user.
pollTime
: The poll interval for account and network changes (in milliseconds). The current recommendation is to poll for account and network changes.
supportedNetworks
: Enforces that the web3 instance is connected to a particular network. If the detected network ID is not in the passed list, the UnsupportedNetwork
screen will be shown. Supported network IDs are: 1
(Mainnet), 3
(Ropsten), 4
(Rinkeby), and 42
(Kovan).
children
: React Components to be rendered upon successful Web3 React initialization.
2. Web3Context
Elements
The Web3Context
consists of the 4 elements below.
{
web3js: ...,
account: ...,
networkId: ...,
reRenderers: {...}
}
Note: Web3 React guarantees that while the children
of Web3Provider
are rendered, none of the Web3Context
elements are null
or undefined
.
web3js
: A web3.js instance instantiated with the current web3 provider.account
: The current active account.networkId
: The current active network ID.reRenderers
: Variables and functions to facilitate the re-rendering of data derived from account
or networkId
(such as a user's balance, which can change over time without their actual account
changing). For how to use these reRenderers, see src/web3Hooks.js. useAccountEffect
and useNetworkEffect
convenience wrappers for useEffect
are available as named exports of web3-react/hooks
; they take care of re-renders automatically.
accountReRenderer
: Forces re-renders of account-derived data.forceAccountReRender
: A function that triggers a global re-render for Hooks depending on accountReRenderer
.networkReRenderer
: Forces re-renders of network-derived data.forceNetworkReRender
: A function that triggers a global re-render for Hooks depending on networkReRenderer
.
3. Web3Consumer
Props
recreateOnNetworkChange
. A flag that controls whether child components are freshly re-initialized upon network changes.
recreateOnAccountChange
. A flag that controls whether child components are freshly re-initialized upon account changes.
Re-initialization is often the desired behavior, though properly written Hooks should not require these flags to be set.
4. withWeb3
Arguments
Flags that can be passed in the second argument to withWeb3
:
recreateOnNetworkChange
. See above.recreateOnAccountChange
. See above.
withWeb3(..., { ... })
Notes
-
Prior art for Web3 React includes:
-
A pure Javascript implementation with some of the same goals: web3-webpacked.
-
A non-Hooks port of web3-webpacked to React that had some problems:
web3-webpacked-react.
-
A React library with some of the same goals but that unfortunately uses the deprecated React Context API and does not use Hooks: react-web3.
-
Right now, Web3 React is opinionated in the sense that it relies on web3.js in lieu of possible alternatives like ethjs or ethers.js. In the future, it's possible that this restriction will be relaxed. It's not clear how this would best be achieved, however, so ideas and comments are welcome. Open an issue or PR!