# React hooks

> @layerhop/react — LayerHopProvider plus useQuote, useSwap, useOrderStatus, useTokens and friends, on top of the SDK and TanStack Query.

Source: https://docs.layerhop.com/sdks/react

`@layerhop/react` adds React hooks for LayerHop swaps on top of the [TypeScript SDK](/sdk) and [TanStack Query](https://tanstack.com/query) v5: wrap your app in `LayerHopProvider`, quote with `useQuote`, and run a whole swap with `useSwap`. It is wallet-agnostic: `useSwap` calls *your* `sign(tx)` callback, so it works with wagmi/viem, ethers or the Solana wallet adapter.

> The hooks never hold keys. They fetch quotes and build **unsigned** transactions; your wallet signs.

## How do I install it?

```bash
npm install @layerhop/react @layerhop/sdk @tanstack/react-query
```

Peer dependencies: `react >= 18`, `@tanstack/react-query >= 5`.

## LayerHopProvider

```tsx
import { LayerHopProvider } from "@layerhop/react";

<LayerHopProvider options={{ integrator: "myapp" }}>
  <App />
</LayerHopProvider>
```

| Prop | Description |
|---|---|
| `client` | A `new LayerHop({...})` instance (or any object with the same methods). Wins over `options`. |
| `options` | [`LayerHopOptions`](/sdk#new-layerhopoptions) for a client the provider creates. |
| `queryClient` | Your TanStack `QueryClient`. If you leave it out, an existing `<QueryClientProvider>` above is reused, or the provider creates one. |

## Quickstart: quote → build → sign → report → track

Amounts are **integer strings in base units** (100 USDC = `"100000000"`).

```tsx
import { useQuote, useSwap } from "@layerhop/react";
import { useAccount, useSendTransaction } from "wagmi";

function Swap() {
  const { address } = useAccount();
  const { sendTransactionAsync } = useSendTransaction();
  const quote = useQuote({
    srcChain: "base", srcToken: "USDC", amount: "100000000",
    dstChain: "solana", dstToken: "SOL",
    sender: address, recipient: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
  });
  const swap = useSwap({
    sign: async (tx) => {
      if (tx.vm !== "evm") throw new Error("connect a Solana wallet for this route");
      // send tx.approval first when present (see Approvals)
      return sendTransactionAsync({ to: tx.to as `0x${string}`, data: tx.data as `0x${string}`, value: BigInt(tx.value) });
    },
  });
  return (
    <button disabled={!quote.data || swap.isBusy} onClick={() => swap.start({ quote: quote.data!.best })}>
      {swap.phase === "idle" ? `Get ${quote.data?.best.dstAmount ?? "…"} lamports` : swap.phase}
    </button>
  );
}
```

## useSwap

`useSwap({ sign, pollIntervalMs?, trackTimeoutMs?, onPhase? })` runs one swap as a state machine:

`idle → quoting → building → awaiting-signature → submitted → tracking → done | error`

1. `start(params)` gets quotes and takes the best one. `start({ quote })` skips quoting.
2. It builds the transaction, then calls `sign(tx, { quote })`. Your callback returns the broadcast tx hash, either as a `string` or as `{ txHash }`. For Solana txs with [`submitViaApi`](/concepts/submit-via-api), return `{ signedTransaction }` (base64) and the hook submits it for you.
3. When the SDK has `reportSubmitted`, the hook reports the hash (`POST /v1/orders/{quoteId}/submitted`). This is best effort: a failed report never fails the swap.
4. It polls the [order status](/concepts/order-tracking) until `filled` → `done`. `refunded` or `failed` → `error` with a `SwapError` (`code` `ORDER_REFUNDED` / `ORDER_FAILED`). Same-chain providers always report `unknown`, which counts as done.

The result is `{ phase, quote, tx, txHash, status, error, start, reset, isBusy }`. `reset()` goes back to `idle` and abandons a run in flight, for example while the wallet prompt is open.

## Other hooks

- `useOrderStream(quoteId)`: live order status over Server-Sent Events (`{ order, isFinal, connected, error }`), reconnecting until the order is final. Needs `@layerhop/sdk` 0.3+. See [Live order status](/guides/live-status).
- `useQuoteStream(params, { intervalMs, reconnect, enabled }?)`: live quotes over Server-Sent Events (`{ data, error, connected }`); `data` is the latest quote set with `seq`. Reopens after the 5-minute stream lifetime (unless `reconnect: false`) and after network errors; stops on client errors. See [Live quotes](/guides/live-quotes).

| Hook | What it does |
|---|---|
| `useQuote(params, { enabled, refetchInterval, refreshMarginSeconds })` | Quotes from every provider. Idle until params are complete and `amount > 0`. `refetchInterval: "auto"` (default) refetches 5 s before the best quote's `expiresAt`. 4xx errors are not retried. |
| `useBuildTx()` | Mutation: `mutate(quoteId)` → the [`BuiltTx`](/sdk#buildtxquoteid). |
| `useOrderStatus(provider, id, { intervalMs, enabled })` | Polls every 3 s until `filled` / `refunded` / `failed`, then stops. Adds `isFinal`. |
| `useChains()` | Every routable chain from [`GET /v1/chains`](/api-reference#list-chains), cached for the session. Falls back to the built-in registry for clients without `chains()`. |
| `useTokens(chain)` | Tokens on one chain from [`GET /v1/tokens`](/api-reference#list-tokens) (first page), or the built-in list for clients without `tokens()`. Idle while `chain` is empty. |
| `useLayerHop()` | The client from the provider. |

Query keys are exported as `layerhopKeys` for invalidation. API failures are `LayerHopApiError`s with a stable [error code](/errors).

## Executing with a wallet

`useSwap` leaves signing to you. To skip writing the `sign` callback, use [`@layerhop/wagmi`](/guides/wallets): `useExecuteQuote()` builds the transaction, checks the allowance and sends approve + swap (+ fee) in one EIP-5792 confirmation when the wallet supports batching (sequential transactions otherwise), then reports the hash. It reads the client from the same `LayerHopProvider`, and `useLayerHopQuote` is this package's `useQuote`. For Solana, `@layerhop/solana` does the same with wallet-adapter, Wallet Standard and embedded wallets. The [wallets guide](/guides/wallets) has snippets for wagmi/Reown, Privy, Dynamic, thirdweb and Coinbase Smart Wallet.
