Keep Wallet Connected on Page Refresh — Web3 Dev

Shmoji
2 min readFeb 1, 2022

Hello, in this tutorial I will show you how to persist a wallet connection on page reload.

To do this, you first need to know how to connect the user to a wallet on your app. You can learn that here:

Once you have an app that can connect to wallets, continue on.

Resources for this tutorial:

Implementing this is super simple. You can think of it like an algorithm with these steps:

1: On connection to wallet, set a variable to true in local storage. Keeping it in local storage will allow us to persist that data on the user’s device.

Code example:

async function connect() {
try {
await activate(injected)
localStorage.setItem('isWalletConnected', true)
} catch (ex) {
console.log(ex)
}
}

2: On disconnect of wallet, set the variable to false in local storage.

Code example:

async function disconnect() {
try {
deactivate()
localStorage.setItem('isWalletConnected', false)
} catch (ex) {
console.log(ex)
}
}

3: On page load, check if the variable in local storage is true. If it is, this means the user was previously connected to a wallet before page refresh, so we need to reconnect them.

Code example:

useEffect(() => {
const connectWalletOnPageLoad = async () => {
if (localStorage?.getItem('isWalletConnected') === 'true') {
try {
await activate(injected)
} catch (ex) {
console.log(ex)
}
}
}
connectWalletOnPageLoad()
}, [])

After implementing these three steps, your app should now automatically reconnect users to their wallet on page refresh.

If anything is still unclear, try watching the video version of this tutorial. If you have any questions, feel free to ask here or on Discord.

Follow my social media to keep up-to-date:

YouTube, Twitch, Twitter, Discord

--

--