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

# React

> Watch queries, page selections and run mutations from React components

`bijection/react` holds a client's calls in components. Every hook answers a
`Result`, so nothing throws on render.

| Hook | Holds |
| - | - |
| `<Bijection client>` | The client for the subtree. |
| `useWatch(fn, args, { seen })` | A watch of a query: `undefined` while loading, then its `Result`. |
| `usePages(fn, args, { size, seen })` | The available prefix of a query that returns `ctx.page(…)`. |
| `useMutation(fn)` | A callable mutation with `pending` and `last`. Pass `once`, `optimistic` and `seen` to the call. |
| `useClientAuth(auth, state)` | Commits the provider's state and reports when the caller's subtree can render. |

`<Bijection>` replaces its descendants when you replace the connection or
the auth adapter reports a change of caller. A token renewal within the
same authorization keeps the subtree. Framed clients on the same
connection also keep the subtree.

When the caller comes from React state, render `<Bijection>` only when
`useClientAuth` returns true. This withdraws the old subtree before the
provider commits the new caller, even if a React `Activity` becomes visible
in that commit. Keep the component calling `useClientAuth` and UI state
that spans sign-ins above the caller-specific subtree.

## Provide the client

Connect once, at module scope, and provide the client above every hook:

```ts apps/main/src/client.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api, connect } from "@bijectionhq/bijection/client";
import type App from "../../../bijection/app";

export const app = api<typeof App>();
export const client = connect("https://example.bijection.cloud", { contract: "discover" });
```

```tsx apps/main/src/main.tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { createRoot } from "react-dom/client";
import { Bijection } from "@bijectionhq/bijection/react";
import { client } from "./client";
import { Notes } from "./notes";

createRoot(document.getElementById("root")!).render(
  <Bijection client={client}>
    <Notes />
  </Bijection>,
);
```

A subtree in another frame nests a framed client:
`<Bijection client={client.in(branch)}>`. See [Frames and trials](https://docs.bijection.com/clients/frames.md).

## Watch data

```tsx apps/main/src/notes.tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useState } from "react";
import { useMutation, useWatch } from "@bijectionhq/bijection/react";
import { app } from "./client";

export function Notes() {
  const listed = useWatch(app.notes.recentNotes);
  const add = useMutation(app.notes.add);
  const [error, setError] = useState<string>();

  async function addNote() {
    const added = await add({ text: "New note" });
    setError(added.ok ? undefined : added.message);
  }

  if (listed === undefined) return <p>Loading…</p>;
  if (!listed.ok) return <p role="alert">{listed.message}</p>;
  return (
    <section>
      <button disabled={add.pending} onClick={() => void addNote()}>Add note</button>
      {error ? <p role="alert">{error}</p> : null}
      <ul>{listed.value.map((note) => <li key={note.id}>{note.text}</li>)}</ul>
    </section>
  );
}
```

`useWatch` answers `undefined` until the first result, then each `Result` as
the query's value changes. Leave out the arguments when the query declares
none. It watches again when the client, the function, the arguments' value
or `seen` changes, so keep arguments stable: build them in render from
primitive values, or with `useMemo`.

Distinct watches catch up independently. Return related values from one
query when they must share a read. See [Realtime](https://docs.bijection.com/realtime.md#one-state-at-a-time).

A hook can't be called conditionally. Pass `null` as the arguments to hold no
watch; the hook then answers `undefined`:

```tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const order = useWatch(app.orders.get, id === null ? null : { id });
```

## Page a selection

`usePages` walks a query that takes `{ size, cursor }` and returns
`ctx.page(selection, { size, cursor })`:

```ts bijection/orders.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, query, role, t, table } from "@bijectionhq/bijection";

export const orders = table({ state: t.string, number: t.string, placed: t.instant }, {
  index: [["state", "placed"]],
});

export const inState = query(
  { allow: [role.signedIn], args: { state: t.string, size: t.number, cursor: t.cursor } },
  (ctx, { state, size, cursor }) =>
    ctx.page(orders.where({ state }).by("placed").descending(), { size, cursor }),
);

export default app({ orders: { items: orders, inState } });
```

```tsx apps/main/src/orders.tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
import { usePages } from "@bijectionhq/bijection/react";
import type OrdersApp from "../../../bijection/orders";

const entries = api<typeof OrdersApp>();

export function PlacedOrders() {
  const placed = usePages(entries.orders.inState, { state: "placed" }, { size: 50 });
  if (placed.result?.ok === false) return <p role="alert">{placed.result.message}</p>;
  return (
    <>
      <ul>{placed.facts.map((order) => <li key={order.id}>{order.number}</li>)}</ul>
      {placed.result === undefined ? <p>Loading…</p> : null}
      {placed.continuation?.kind === "more" ? <button onClick={placed.loadMore}>More</button> : null}
      {placed.continuation?.kind === "limit" ? <p>Refine your search to see more orders.</p> : null}
    </>
  );
}
```

Pass the query's other arguments. The hook supplies `size` and starts with
`cursor: null`. It follows each page's `next`. A changed cursor replaces
the dependent pages, and `facts` keeps the available prefix while the
replacements load. `result` is `undefined` while a page is loading and
carries the refusal if a page in the walk refuses.

The deployment walks the live prefix at one held version. The continuation
is `end` when the query returned no cursor, `more` when `loadMore()` can
extend the live prefix, and `limit` when additional rows exist beyond the
live bound. Both `more` and `limit` carry the cursor. A client can use the
cursor in an explicit paging query. A live prefix holds up to 16 pages over
HTTP and one page over a custom transport without prefix support. The
continuation is `undefined` while the requested prefix is loading or refused.
A change of client, query, arguments, `size`, `seen`, or caller starts a new
prefix.

Use `useWatch` for values that must share one evaluation, including a
single evaluation instant for time-sensitive values.

## Change data

`useMutation(fn)` returns a function that runs the mutation and answers its
`Result`. `pending` is true while a call is in flight, and `last` is the last
result. An unsent mutation returns `Withdrawn` if its provider's connection
or reported caller changes. A mutation that already reached the deployment
can still return its result.

Each call gets a fresh `once` by default. To retry an `Unknown`, pass the
same arguments and the refusal's `once` as `add(args, { once })`. The
refusal is available from the call's result and from `last` until another
call settles. See [Retries and read-your-writes](https://docs.bijection.com/clients/requests.md).

`optimistic` edits watched values while a mutation is pending and until
the affected watches catch up to a successful commit. See
[Optimistic updates](https://docs.bijection.com/clients/react/optimistic-updates.md).

## Read your own writes

A committed mutation's result carries its `version`. After the latest
mutation succeeds, pass its `version` as `seen` to read at least that state.

```tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const add = useMutation(app.notes.add);
const added = add.last;
const listed = useWatch(app.notes.recentNotes, {}, {
  seen: added?.ok ? added.version : undefined,
});
```

## Authenticate

Pass an auth adapter as `connect(url, { contract: "discover", token })` and feed it the provider's
state with `useClientAuth`. See [Connect and authenticate](https://docs.bijection.com/clients/react/configuration.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.