Cache a MetaMask Wallet Address in localStorage

Ryan Harris
InstructorRyan Harris
Share this video with your friends

Social Share Links

Send Tweet

Since we are storing the user’s wallet address in React state, it is lost when the dApp is reloaded. To fix this, we’ll cache the address in localStorage.

We’ll use the useEffect hook to look for an address in localStorage if there isn’t one in local state.

Instructor: [0:00] Right now, if a user refreshes the browser when connected, it seems our application has lost the connection. Let's improve this user experience by caching the value in local storage.

[0:11] The first thing we're going to do is come to our onConnect callback here for our connect component. We're going to say window.localStorage.setItem. We're going to call this item nfTicksAddress, and we'll set its value to address.

[0:28] In our onDisconnect function, we want to do the inverse. We'll say, window. localStorage.removeItem, and pass it the same item name, nfTicksAddress. Let's come to the top of the file and import { useEffect } from 'react'. Come down below. We'll add a new effect, useEffect.

[0:54] We'll add address to the dependency array, since we only want this hook to run when the address changes. Inside, let's add a conditional. If not address, then let's look for one in local storage.

[1:08] We'll say const previousAddress = window.localStorage.getItem("nfTicksAddress"). If we don't have address set in our local state, but we do have previous address and local storage, let's set that to our local state. If previousAddress, set address to the previous address.

[1:38] If you come back and refresh and connect again, you'll see we no longer lose the address in our UI when we refresh the browser.

[1:48] To review, we've used local storage in the browser to cache the connected metamask wallet's address.