Skip to content

useAccountEffect

React hook for handling Starknet account connection and disconnection events.

Import

import { useAccountEffect } from "starkweb/react";

Usage

index.tsx
import { useAccountEffect } from "starkweb/react";
 
function App() {
  useAccountEffect({
    onConnect(data) {
      console.log("Connected!", data);
    },
    onDisconnect() {
      console.log("Disconnected!");
    },
  });
}

Parameters

import { type UseAccountEffectParameters } from "starkweb/react";

config

Config | undefined

Config to use instead of retrieving from the nearest StarkwebProvider.

index.tsx
import { useAccountEffect } from "starkweb/react";
import { config } from "./config"; 
 
function App() {
  useAccountEffect({
    config, 
    onConnect(data) {
      console.log("Connected!", data);
    },
    onDisconnect() {
      console.log("Disconnected!");
    },
  });
}

onConnect

((data: { address: `0x${string}`; addresses: readonly [`0x${string}`, ...`0x${string}`[]]; chain: Chain | undefined; chainId: number; connector: Connector; isReconnected: boolean }) => void) | undefined

Callback that is called when accounts are connected.

index.tsx
import { useAccountEffect } from "starkweb/react";
 
function App() {
  useAccountEffect({
    onConnect(data) {

      console.log("Connected!", data); 
    }, 
  });
}

onDisconnect

(() => void) | undefined

Callback that is called when no more accounts are connected.

index.tsx
import { useAccountEffect } from "starkweb/react";
 
function App() {
  useAccountEffect({
    onDisconnect() {

      console.log("Disconnected!"); 
    }, 
  });
}

Examples

Basic Usage

basic.tsx
import { useAccountEffect } from "starkweb/react";
 
function WalletEvents() {
  useAccountEffect({
    onConnect(data) {
      const { address, chainId, isReconnected } = data;
      console.log(`Connected to ${address} on chain ${chainId}`);
      console.log(
        `Connection type: ${isReconnected ? "Reconnected" : "New connection"}`
      );
    },
    onDisconnect() {
      console.log("Wallet disconnected");
    },
  });
 
  return <div>Monitoring wallet events...</div>;
}

With Contract Interaction

contract-interaction.tsx
import { useAccountEffect } from "starkweb/react";
import { Contract } from "starkweb/contract";
import { useState } from "react";
 
function TokenWatcher() {
  const [balance, setBalance] = useState<string>();
 
  useAccountEffect({
    onConnect(data) {
      // ERC20 token contract
      const contract = new Contract(
        "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
        [
          {
            name: "balanceOf",
            type: "function",
            inputs: [{ name: "account", type: "felt" }],
            outputs: [{ name: "balance", type: "Uint256" }],
            stateMutability: "view",
          },
        ],
        data.connector
      );
 
      // Get token balance
      contract
        .balanceOf(data.address)
        .then((balance) => setBalance(balance.toString()));
    },
    onDisconnect() {
      setBalance(undefined);
    },
  });
 
  return (
    <div>
      {balance ? `Token Balance: ${balance}` : "Connect wallet to view balance"}
    </div>
  );
}

With Connection Status

connection-status.tsx
import { useAccountEffect } from "starkweb/react";
import { useState } from "react";
 
function ConnectionTracker() {
  const [status, setStatus] = useState<string>("Waiting for wallet...");
  const [chainName, setChainName] = useState<string>();
 
  useAccountEffect({
    onConnect(data) {
      setStatus(data.isReconnected ? "Reconnected" : "Connected");
      setChainName(data.chain?.name);
    },
    onDisconnect() {
      setStatus("Disconnected");
      setChainName(undefined);
    },
  });
 
  return (
    <div>
      <div>Status: {status}</div>
      {chainName && <div>Network: {chainName}</div>}
    </div>
  );
}

With Error Handling

error-handling.tsx
import { useAccountEffect } from "starkweb/react";
import { useState } from "react";
 
function SafeWalletMonitor() {
  const [error, setError] = useState<Error>();
  const [connectionInfo, setConnectionInfo] = useState<{
    address: string;
    chain: string;
  }>();
 
  useAccountEffect({
    onConnect(data) {
      try {
        // Validate chain support
        if (!data.chain) {
          throw new Error("Unsupported network");
        }
 
        // Store connection info
        setConnectionInfo({
          address: data.address,
          chain: data.chain.name,
        });
        setError(undefined);
      } catch (err) {
        setError(err instanceof Error ? err : new Error("Connection failed"));
        setConnectionInfo(undefined);
      }
    },
    onDisconnect() {
      setConnectionInfo(undefined);
      setError(undefined);
    },
  });
 
  if (error) {
    return <div>Error: {error.message}</div>;
  }
 
  if (connectionInfo) {
    return (
      <div>
        <div>Connected to: {connectionInfo.address}</div>
        <div>Network: {connectionInfo.chain}</div>
      </div>
    );
  }
 
  return <div>Waiting for wallet connection...</div>;
}