Cache a MetaMask Wallet Address in localStorage

Ryan Harris
InstructorRyan Harris
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

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.

~ 12 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today