Skip to content

useClient

Hook for getting Client instance.

Import

import { useClient } from "starkweb/react";

Usage

index.tsx
import { useClient } from "starkweb/react";
 
function App() {
  const client = useClient();
}

Parameters

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

chainId

config["chains"][number]["id"] | undefined

ID of chain to use when getting Client.

index.ts
import { useClient } from "starkweb/react";
import { mainnet } from "starkweb/react/chains"; 
 
function App() {
  const client = useClient({
    chainId: mainnet.chain_id, 
  });
}

config

Config | undefined

Config to use instead of retrieving from the nearest StarkwebProvider.

index.tsx
import { useClient } from "starkweb/react";
import { config } from "./config"; 
 
function App() {
  const client = useClient({
    config, 
  });
}

Return Type

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

Client | undefined

Client instance.

Examples

Basic Usage

basic.tsx
import { useClient } from "starkweb/react";
 
function ClientInfo() {
  const client = useClient();
 
  if (!client) return <div>No client available</div>;
 
  return (
    <div>
      <div>Client UID: {client.uid}</div>
      <div>Transport Type: {client.transport.type}</div>
    </div>
  );
}

With Chain Selection

chain-selection.tsx
import { useClient } from "starkweb/react";
import { mainnet } from "starkweb/chains";
import { useState } from "react";
 
function BlockFetcher() {
  const [blockNumber, setBlockNumber] = useState<bigint>();
  const client = useClient({
    chainId: mainnet.chain_id,
  });
 
  async function fetchLatestBlock() {
    if (!client) return;
    const block = await client.getBlockNumber();
    setBlockNumber(block);
  }
 
  return (
    <div>
      <button onClick={fetchLatestBlock}>Fetch Latest Block</button>
      {blockNumber && <div>Latest Block: {blockNumber.toString()}</div>}
    </div>
  );
}

With Custom Config

custom-config.tsx
import { useClient } from "starkweb/react";
import { createConfig, http } from "starkweb/core";
import { mainnet } from "starkweb/chains";
 
const config = createConfig({
  chains: [mainnet],
  transports: {
    [mainnet.chain_id]: http(),
  },
});
 
function CustomClientInfo() {
  const client = useClient({
    config,
  });
 
  return (
    <div>
      {client ? (
        <div>Custom client connected</div>
      ) : (
        <div>Custom client not available</div>
      )}
    </div>
  );
}