What is generally best practice way to set up a web3 instance?
useRefuseState- Using/not using
useEffect
- Using props/context to pass a single instance to other components, or re-instantiating it in each component
Background: I tried setting up a web3 instance with useRef, however it only passed null through context. I found though that using useState and not using useEffect worked. Curious about best practice though.
export default function MyApp({ Component, pageProps }) {
/* ⨯ Passed through context as null */
const web3 = useRef(null);
useEffect(() => {
if (window.ethereum) {
web3.current = new Web3(window.ethereum)
}
}, [])
/* ✓ Passed through context as web3 instance */
const [web3, setWeb3] = useState(null)
useEffect(() => {
if (window.ethereum) {
const w3 = new Web3(window.ethereum)
setWeb3(w3)
}
}, [])
/* ✓ Passed through context as web3 instance */
if (window.ethereum) {
const w3 = new Web3(window.ethereum)
setWeb3(w3) // ✓
web3.current = w3 // ✓
}
return (
<Web3Context.Provider value={web3.current ?? web3}>
<Component {...pageProps} />
</Web3Context.Provider>
)
}