i am using the WalletConnectButton from @solana/wallet-adapter-react-ui in my React app. I want to execute additional logic when the user connects and disconnects their wallet. Is there a way to do that? thanks

1 Answer 1


Since you're using React the easiest way to do this would be with a useEffect hook.

import { useWallet } from '@solana/wallet-adapter-react';
import { useEffect, useState } from 'react';

export default function MyComponent() {
  const { publicKey } = useWallet()
  const [hasConnected, setHasConnected] = useState(false)

  useEffect(() => {
    if(publicKey) {
      // do stuff after connect
    } else {
      if(hasConnected) {
        // do stuff after disconnect
  }, [publicKey])

  return <div>whatever</div>

Since publicKey is in the dependency array, that effect will re-run with the newest value of publicKey available every time it changes.

  • the problem with this is "// do stuff after disconnect" line gets called when you refresh the page
    – s0lana
    Commented Sep 20, 2022 at 18:12
  • I edited the answer to show how to avoid this. You can add a hasConnected state, default it to false, set it to true in the if(publicKey) branch, and then condition the disconnect logic on that being true.
    – Callum M
    Commented Sep 20, 2022 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.