> ## Documentation Index
> Fetch the complete documentation index at: https://docs.privacyboost.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Multi-Chain

> Use the useChain hook for multi-chain operations in React

# Multi-Chain

This guide covers using the `useChain` hook and `ChainClient` to build React applications that operate across multiple blockchains.

<Info>
  For an overview of multi-chain concepts, see [Multi-Chain Concepts](/sdk/concepts/multi-chain).
</Info>

## The `useChain` Hook

`useChain` returns a `ChainClient` for a specific chain, memoized to prevent unnecessary re-renders:

```tsx theme={null}
import { useChain } from '@sunnyside-io/privacy-boost-react';

function MyComponent() {
  const ethereum = useChain({ serverUrl: 'https://eth.example.com' });

  if (!ethereum) return <div>Loading SDK...</div>;

  return <div>Chain ID: {ethereum.chainId}</div>;
}
```

`useChain` returns `null` if the parent SDK is not yet initialized. Chain clients are cached by `serverUrl`, so calling `useChain` with the same URL in multiple components returns the same instance.

## Setup

Wrap your app with `PrivacyBoostProvider` as usual. The provider initializes the parent SDK, and `useChain` creates chain clients from it:

```tsx theme={null}
import { PrivacyBoostProvider } from '@sunnyside-io/privacy-boost-react';

function App() {
  return (
    <PrivacyBoostProvider config={{
      serverUrl: 'https://op.example.com',
      appId: 'my-app',
    }}>
      <MultiChainApp />
    </PrivacyBoostProvider>
  );
}
```

## Authentication

Each chain client must be authenticated independently. Use the wallet adapter from `useAuth` or create one manually:

```tsx theme={null}
import { useChain, useAuth } from '@sunnyside-io/privacy-boost-react';
import { useState } from 'react';

function ChainConnect({ serverUrl, name }: { serverUrl: string; name: string }) {
  const chain = useChain({ serverUrl });
  const [authenticated, setAuthenticated] = useState(false);

  const connect = async () => {
    if (!chain) return;
    await chain.authenticate(walletAdapter);
    setAuthenticated(true);
  };

  if (!chain) return <div>Loading...</div>;

  if (!authenticated) {
    return <button onClick={connect}>Connect to {name}</button>;
  }

  return (
    <div>
      <p>Connected to {name} (chain {chain.chainId})</p>
      <ChainOperations chain={chain} />
    </div>
  );
}
```

## Multi-Chain Dashboard

Here's a pattern for building a multi-chain dashboard:

```tsx theme={null}
import { useChain } from '@sunnyside-io/privacy-boost-react';

const CHAINS = [
  { name: 'Ethereum', serverUrl: 'https://eth.example.com' },
  { name: 'Base', serverUrl: 'https://base.example.com' },
  { name: 'Optimism', serverUrl: 'https://op.example.com' },
];

function MultiChainDashboard() {
  return (
    <div>
      {CHAINS.map((chain) => (
        <ChainPanel key={chain.serverUrl} {...chain} />
      ))}
    </div>
  );
}

function ChainPanel({ name, serverUrl }: { name: string; serverUrl: string }) {
  const chain = useChain({ serverUrl });

  if (!chain) return <div>{name}: Loading...</div>;
  if (!chain.isAuthenticated) return <div>{name}: Not connected</div>;

  return (
    <div>
      <h3>{name}</h3>
      <ChainBalances chain={chain} />
      <ChainDeposit chain={chain} />
    </div>
  );
}
```

## Chain-Scoped Components

Build reusable components that accept a `ChainClient`:

### Balance Display

```tsx theme={null}
import type { ChainClient } from '@sunnyside-io/privacy-boost-react';
import { useState, useEffect } from 'react';

function ChainBalances({ chain }: { chain: ChainClient }) {
  const [shielded, setShielded] = useState<bigint>(0n);

  useEffect(() => {
    chain.vault.getBalance('0x...token').then((b) => setShielded(b.shielded));
  }, [chain]);

  return <p>Shielded: {shielded.toString()}</p>;
}
```

### Deposit Form

```tsx theme={null}
import type { ChainClient } from '@sunnyside-io/privacy-boost-react';
import { useState } from 'react';

function ChainDeposit({ chain }: { chain: ChainClient }) {
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);

  const handleShield = async () => {
    setLoading(true);
    try {
      await chain.vault.shield({
        tokenAddress: '0x...',
        amount: BigInt(amount),
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <input value={amount} onChange={(e) => setAmount(e.target.value)} />
      <button onClick={handleShield} disabled={loading}>
        {loading ? 'Depositing...' : 'Deposit'}
      </button>
    </div>
  );
}
```

### Transfer Form

```tsx theme={null}
function ChainTransfer({ chain }: { chain: ChainClient }) {
  const [to, setTo] = useState('');
  const [amount, setAmount] = useState('');

  const handleSend = async () => {
    await chain.vault.send({
      to,
      tokenAddress: '0x...',
      amount: BigInt(amount),
    });
  };

  return (
    <div>
      <input value={to} onChange={(e) => setTo(e.target.value)} placeholder="Privacy address" />
      <input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Amount" />
      <button onClick={handleSend}>Send</button>
    </div>
  );
}
```

## Chain Switching

Build a chain selector that lets users switch between chains:

```tsx theme={null}
import { useChain } from '@sunnyside-io/privacy-boost-react';
import { useState } from 'react';

const CHAINS = {
  ethereum: { name: 'Ethereum', serverUrl: 'https://eth.example.com' },
  base: { name: 'Base', serverUrl: 'https://base.example.com' },
};

function ChainSwitcher() {
  const [selected, setSelected] = useState<keyof typeof CHAINS>('ethereum');
  const chain = useChain(CHAINS[selected]);

  return (
    <div>
      <select value={selected} onChange={(e) => setSelected(e.target.value as keyof typeof CHAINS)}>
        {Object.entries(CHAINS).map(([key, { name }]) => (
          <option key={key} value={key}>{name}</option>
        ))}
      </select>

      {chain && <ChainOperations chain={chain} />}
    </div>
  );
}
```

## Available Hooks

| Hook                | Purpose                                              |
| ------------------- | ---------------------------------------------------- |
| `useChain(config)`  | Get a `ChainClient` for a specific chain             |
| `useAuth()`         | Wallet connection and authentication (primary chain) |
| `useVault()`        | Vault operations (primary chain)                     |
| `useBalances()`     | Reactive balances (primary chain)                    |
| `useTransactions()` | Transaction history (primary chain)                  |
| `usePrivacyBoost()` | Direct SDK access                                    |

<Info>
  `useAuth`, `useVault`, `useBalances`, and `useTransactions` operate on the primary chain configured in the provider. For other chains, use `useChain` and access resources directly via the `ChainClient` (e.g., `chain.vault`, `chain.transactions`).
</Info>

## Next Steps

* [Provider Setup](./provider-setup) — configure the provider
* [Deposits Guide](./deposits) — shield operations
* [Transfers Guide](./transfers) — private transfers
* [Multi-Chain Concepts](/sdk/concepts/multi-chain) — architecture overview
