<!--
Sitemap:
- [MBGA · Reactive Primitives for Spark](/index)
- [Acknowledgments](/acknowledgments)
- [API Reference](/api/)
- [Connectors](/connectors/)
- [Examples](/examples/)
- [Flashnet](/flashnet/)
- [Getting Started](/getting-started)
- [Installation](/installation)
- [Kit](/kit/)
- [Configuration](/api/configuration)
- [Core Actions](/api/core-actions)
- [React Hooks](/api/hooks)
- [Types & Errors](/api/types)
- [Custom Connectors](/connectors/custom)
- [Sats Connect (Xverse)](/connectors/sats-connect)
- [Spark SDK](/connectors/spark-sdk)
- [Wallet Standard](/connectors/wallet-standard)
- [Flashnet Authentication](/flashnet/authentication)
- [Next.js](/frameworks/nextjs)
- [Vite](/frameworks/vite)
- [AccountModal](/kit/account-modal)
- [ConnectButton](/kit/connect-button)
- [ConnectModal](/kit/connect-modal)
-->

# React Hooks

All hooks are exported from `mbga`. They must be used inside a `<MbgaProvider>`.

Every hook accepts an optional `config` parameter to use a specific config instead of the one from context.

## Connection Hooks

### `useConfig`

Returns the current MBGA config from context.

```ts
import { useConfig } from 'mbga'

function MyComponent() {
  const config = useConfig()
  console.log(config.network) // SparkNetwork
}
```

**Returns:** `Config`

**Throws:** `MbgaProviderNotFoundError` if used outside `<MbgaProvider>`.

### `useDisconnect`

Disconnects the current wallet (or a specific connector).

```tsx
import { useDisconnect } from 'mbga'

function DisconnectButton() {
  const { disconnect, isPending } = useDisconnect()

  return (
    <button disabled={isPending} onClick={() => disconnect()}>
      Disconnect
    </button>
  )
}
```

**Returns:** `UseDisconnectReturnType`

```ts
type UseDisconnectReturnType = {
  disconnect: (variables?: { connector?: Connector }) => void
  disconnectAsync: (variables?: { connector?: Connector }) => Promise<void>
  error: DisconnectErrorType | null
  isError: boolean
  isIdle: boolean
  isPending: boolean
  isSuccess: boolean
  reset: () => void
  status: 'error' | 'idle' | 'pending' | 'success'
}
```

Pass `{ connector }` to disconnect a specific connector. Without it, the current active connector is disconnected.

### `useConnectors`

Returns the list of all configured connectors. Re-renders when connectors change.

```tsx
import { useConnectors } from 'mbga'

function ConnectorList() {
  const connectors = useConnectors()

  return (
    <ul>
      {connectors.map((c) => (
        <li key={c.uid}>{c.name} ({c.type})</li>
      ))}
    </ul>
  )
}
```

**Returns:** `readonly Connector[]`

### `useWatchConnection`

Watches for connection state changes and fires callbacks. Does not cause re-renders itself.

```tsx
import { useWatchConnection } from 'mbga'

function ConnectionWatcher() {
  useWatchConnection({
    onChange(connection, prevConnection) {
      console.log('Connection changed:', connection.status)
    },
    onConnect(connection) {
      console.log('Connected:', connection.accounts)
    },
    onDisconnect(prevConnection) {
      console.log('Disconnected from:', prevConnection.connector?.name)
    },
  })

  return null
}
```

**Parameters:** `UseWatchConnectionParameters`

```ts
type UseWatchConnectionParameters = {
  config?: Config | undefined
  onChange?(
    connection: GetConnectionReturnType,
    prevConnection: GetConnectionReturnType,
  ): void
  onConnect?(connection: GetConnectionReturnType): void
  onDisconnect?(prevConnection: GetConnectionReturnType): void
}
```

**Returns:** `void`

### `useGetTransaction`

Looks up a transaction by its ID.

```tsx
import { useGetTransaction } from 'mbga'

function TransactionStatus({ txId }: { txId: string }) {
  const { data, isLoading } = useGetTransaction({ id: txId })

  if (isLoading) return <p>Loading...</p>

  return (
    <div>
      <p>Status: {data?.status}</p>
      <p>Amount: {data?.amount.toString()} sats</p>
      <p>Direction: {data?.direction}</p>
      <p>Type: {data?.type}</p>
    </div>
  )
}
```

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | `string` | Transaction ID to look up |
| `enabled` | `boolean` | Whether the query should execute |

**Return data:**

```ts
type GetTransactionReturnType = {
  id: string
  status: string
  amount: bigint
  direction: 'incoming' | 'outgoing'
  createdAt: Date | undefined
  updatedAt: Date | undefined
  type: string
}
```

### `useCreateInvoice`

Generates a Lightning invoice to receive payments.

```tsx
import { useCreateInvoice } from 'mbga'

function ReceivePayment() {
  const { createInvoice, data, isPending } = useCreateInvoice()

  return (
    <div>
      <button
        onClick={() => createInvoice({ amount: 1000n, memo: 'Coffee' })}
        disabled={isPending}
      >
        Create Invoice for 1000 sats
      </button>
      {data && <code>{data.invoice}</code>}
    </div>
  )
}
```

**Mutation variables:**

```ts
type CreateInvoiceParameters = {
  amount: bigint   // Amount in satoshis
  memo?: string    // Optional description
}
```

**Return data:**

```ts
type CreateInvoiceReturnType = {
  invoice: string  // BOLT11 invoice string
  id?: string      // Internal request ID (for use with waitForPayment)
}
```

### `useSignMessage`

Signs a message with the connected wallet.

```tsx
import { useSignMessage } from 'mbga'

function SignButton() {
  const { signMessage, data } = useSignMessage()

  return (
    <div>
      <button onClick={() => signMessage({ message: 'Hello MBGA' })}>
        Sign Message
      </button>
      {data && <p>Signature: {data.signature}</p>}
    </div>
  )
}
```

**Mutation variables:**

```ts
type SignMessageParameters = {
  message: string    // Message to sign
  address?: string   // Address to sign with (defaults to current account)
}
```

**Return data:** `{ signature: string }`
