> ## 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.

# Module: react

> Tools to integrate Bijection into React applications.

Tools to integrate Bijection into React applications.

This module contains:

1. [BijectionReactClient](/api/classes/react.BijectionReactClient), a client for using Bijection in React.
2. [BijectionProvider](/api/modules/react#bijectionprovider), a component that stores this client in React context.
3. [Authenticated](/api/modules/react#authenticated), [Unauthenticated](/api/modules/react#unauthenticated), [AuthLoading](/api/modules/react#authloading) and [AuthRefreshing](/api/modules/react#authrefreshing) helper auth components.
4. Hooks [useQuery](/api/modules/react#usequery), [useMutation](/api/modules/react#usemutation), [useAction](/api/modules/react#useaction) and more for accessing this
   client from your React components.

## Usage

### Creating the client

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { BijectionReactClient } from "bijection/react";

// typically loaded from an environment variable
const address = "https://small-mouse-123.bijection.cloud"
const bijection = new BijectionReactClient(address);
```

### Storing the client in React Context

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { BijectionProvider } from "bijection/react";

<BijectionProvider client={bijection}>
  <App />
</BijectionProvider>
```

### Using the auth helpers

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { Authenticated, Unauthenticated, AuthLoading, AuthRefreshing } from "bijection/react";

<Authenticated>
  Logged in
</Authenticated>
<Unauthenticated>
  Logged out
</Unauthenticated>
<AuthLoading>
  Still loading
</AuthLoading>
<AuthRefreshing>
  Refreshing token...
</AuthRefreshing>
```

### Using React hooks

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useQuery, useMutation } from "bijection/react";
import { api } from "../bijection/_generated/api";

function App() {
  const counter = useQuery(api.getCounter.default);
  const increment = useMutation(api.incrementCounter.default);
  // Your component here!
}
```

## Classes

* [BijectionReactClient](/api/classes/react.BijectionReactClient)

## Interfaces

* [ReactMutation](/api/interfaces/react.ReactMutation)
* [ReactAction](/api/interfaces/react.ReactAction)
* [Watch](/api/interfaces/react.Watch)
* [WatchQueryOptions](/api/interfaces/react.WatchQueryOptions)
* [MutationOptions](/api/interfaces/react.MutationOptions)
* [BijectionReactClientOptions](/api/interfaces/react.BijectionReactClientOptions)

## References

### AuthTokenFetcher

Re-exports [AuthTokenFetcher](/api/modules/browser#authtokenfetcher)

***

### QueryOptions

Re-exports [QueryOptions](/api/modules/browser#queryoptions)

## Type Aliases

### BijectionAuthState

Ƭ **BijectionAuthState**: `Object`

Type representing the state of an auth integration with Bijection.

* `isLoading`: the client is still resolving the initial auth state and
  waiting for the server to confirm the current token.
* `isAuthenticated`: the server has confirmed the current token.
* `isRefreshing`: the server rejected a previously-confirmed token and the
  socket is paused while a replacement is fetched. Only ever `true` when
  `isAuthenticated` is also `true`. Routine background token rotation does
  not trigger this state.

#### Type declaration

| Name | Type |
| :- | :- |
| `isLoading` | `boolean` |
| `isAuthenticated` | `boolean` |
| `isRefreshing` | `boolean` |

***

### OptionalRestArgsOrSkip

Ƭ **OptionalRestArgsOrSkip**\<`FuncRef`>: [`FunctionArgs`](/api/modules/server#functionargs)\<`FuncRef`> extends `EmptyObject` ? \[args?: EmptyObject | "skip"] : \[args: FunctionArgs\<FuncRef> | "skip"]

#### Type parameters

| Name | Type |
| :- | :- |
| `FuncRef` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`any`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`any`> |

***

### UseQueryResult

Ƭ **UseQueryResult**\<`QueryResult`, `ThrowOnError`>: \{ `status`: `"pending"`  } | \{ `status`: `"success"` ; `data`: `QueryResult`  } | `ThrowOnError` extends `true` ? `never` : \{ `status`: `"error"` ; `error`: `Error`  }

Result returned by object-form [useQuery\_experimental](/api/modules/react#usequery_experimental).

#### Type parameters

| Name | Type |
| :- | :- |
| `QueryResult` | `QueryResult` |
| `ThrowOnError` | extends `boolean` = `false` |

***

### Preloaded

Ƭ **Preloaded**\<`Query`>: `Object`

The preloaded query payload, which should be passed to a client component
and passed to [usePreloadedQuery](/api/modules/react#usepreloadedquery).

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`"query"`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`"query"`> |

#### Type declaration

| Name | Type |
| :- | :- |
| `__type` | `Query` |
| `_name` | `string` |
| `_argsJSON` | `string` |
| `_valueJSON` | `string` |

***

### PaginatedQueryReference

Ƭ **PaginatedQueryReference**: [`FunctionReference`](/api/modules/server#functionreference)\<`"query"`, `"public"`, \{ `paginationOpts`: [`PaginationOptions`](/api/interfaces/server.PaginationOptions)  }, [`PaginationResult`](/api/interfaces/server.PaginationResult)\<`any`>>

A [FunctionReference](/api/modules/server#functionreference) that is usable with [usePaginatedQuery](/api/modules/react#usepaginatedquery).

This function reference must:

* Refer to a public query
* Have an argument named "paginationOpts" of type [PaginationOptions](/api/interfaces/server.PaginationOptions)
* Have a return type of [PaginationResult](/api/interfaces/server.PaginationResult).

***

### UsePaginatedQueryResult

Ƭ **UsePaginatedQueryResult**\<`Item`>: \{ `results`: `Item`\[] ; `loadMore`: (`numItems`: `number`) => `void`  } & \{ `status`: `"LoadingFirstPage"` ; `isLoading`: `true`  } | \{ `status`: `"CanLoadMore"` ; `isLoading`: `false`  } | \{ `status`: `"LoadingMore"` ; `isLoading`: `true`  } | \{ `status`: `"Exhausted"` ; `isLoading`: `false`  }

The result of calling the [usePaginatedQuery](/api/modules/react#usepaginatedquery) hook.

This includes:

* `results` - An array of the currently loaded results.
* `isLoading` - Whether the hook is currently loading results.
* `status` - The status of the pagination. The possible statuses are:
  * "LoadingFirstPage": The hook is loading the first page of results.
  * "CanLoadMore": This query may have more items to fetch. Call `loadMore` to
    fetch another page.
  * "LoadingMore": We're currently loading another page of results.
  * "Exhausted": We've paginated to the end of the list.
* `loadMore(n)` A callback to fetch more results. This will only fetch more
  results if the status is "CanLoadMore".

#### Type parameters

| Name |
| :- |
| `Item` |

***

### PaginationStatus

Ƭ **PaginationStatus**: [`UsePaginatedQueryResult`](/api/modules/react#usepaginatedqueryresult)\<`any`>\[`"status"`]

The possible pagination statuses in [UsePaginatedQueryResult](/api/modules/react#usepaginatedqueryresult).

This is a union of string literal types.

***

### PaginatedQueryArgs

Ƭ **PaginatedQueryArgs**\<`Query`>: [`Expand`](/api/modules/server#expand)\<[`BetterOmit`](/api/modules/server#betteromit)\<[`FunctionArgs`](/api/modules/server#functionargs)\<`Query`>, `"paginationOpts"`>>

Given a [PaginatedQueryReference](/api/modules/react#paginatedqueryreference), get the type of the arguments
object for the query, excluding the `paginationOpts` argument.

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

***

### PaginatedQueryItem

Ƭ **PaginatedQueryItem**\<`Query`>: [`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`>\[`"page"`]\[`number`]

Given a [PaginatedQueryReference](/api/modules/react#paginatedqueryreference), get the type of the item being
paginated over.

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

***

### UsePaginatedQueryReturnType

Ƭ **UsePaginatedQueryReturnType**\<`Query`>: [`UsePaginatedQueryResult`](/api/modules/react#usepaginatedqueryresult)\<[`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`>>

The return type of [usePaginatedQuery](/api/modules/react#usepaginatedquery).

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

***

### UsePaginatedQueryOptions

Ƭ **UsePaginatedQueryOptions**\<`Query`, `ThrowOnError`>: `Object`

Options for object-form [usePaginatedQuery\_experimental](/api/modules/react#usepaginatedquery_experimental).

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |
| `ThrowOnError` | extends `boolean` = `false` |

#### Type declaration

| Name | Type | Description |
| :- | :- | :- |
| `query` | `Query` | - |
| `args` | [`PaginatedQueryArgs`](/api/modules/react#paginatedqueryargs)\<`Query`> \| `"skip"` | - |
| `initialNumItems` | `number` | - |
| `throwOnError?` | `ThrowOnError` | When `true` (default for positional form), errors are thrown and caught by an error boundary. When `false` (default for object form), errors are returned as `{ status: "Error", error: Error }` instead of being thrown. |

***

### UsePaginatedQueryObjectReturnType

Ƭ **UsePaginatedQueryObjectReturnType**\<`Query`, `ThrowOnError`>: \{ `data`: [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`>\[] | `undefined` ; `status`: `"pending"` ; `canLoadMore`: `false` ; `isLoading`: `true` ; `error`: `undefined` ; `loadMore`: (`numItems`: `number`) => `void`  } | \{ `data`: [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`>\[] ; `status`: `"success"` ; `canLoadMore`: `boolean` ; `isLoading`: `false` ; `error`: `undefined` ; `loadMore`: (`numItems`: `number`) => `void`  } | `ThrowOnError` extends `true` ? `never` : \{ `data`: [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`>\[] ; `status`: `"error"` ; `canLoadMore`: `false` ; `isLoading`: `false` ; `error`: `Error` ; `loadMore`: (`numItems`: `number`) => `void`  }

Return type of the object-form [usePaginatedQuery\_experimental](/api/modules/react#usepaginatedquery_experimental) overload.

Uses lowercase query status (`"pending" | "success" | "error"`) and a
`canLoadMore` boolean instead of the TitleCase pagination status strings
used by the positional form.

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |
| `ThrowOnError` | extends `boolean` = `false` |

***

### RequestForQueries

Ƭ **RequestForQueries**: `Record`\<`string`, \{ `query`: [`FunctionReference`](/api/modules/server#functionreference)\<`"query"`> ; `args`: `Record`\<`string`, [`Value`](/api/modules/values#value)>  }>

An object representing a request to load multiple queries.

The keys of this object are identifiers and the values are objects containing
the query function and the arguments to pass to it.

This is used as an argument to [useQueries](/api/modules/react#usequeries).

## Functions

### useBijectionAuth

▸ **useBijectionAuth**(): `Object`

Get the [BijectionAuthState](/api/modules/react#bijectionauthstate) within a React component.

This relies on a Bijection auth integration provider being above in the React
component tree. See [BijectionAuthState](/api/modules/react#bijectionauthstate) for the meaning of each field.

#### Returns

`Object`

The current [BijectionAuthState](/api/modules/react#bijectionauthstate).

| Name | Type |
| :- | :- |
| `isLoading` | `boolean` |
| `isAuthenticated` | `boolean` |
| `isRefreshing` | `boolean` |

***

### BijectionProviderWithAuth

▸ **BijectionProviderWithAuth**(`«destructured»`): `Element`

A replacement for [BijectionProvider](/api/modules/react#bijectionprovider) which additionally provides
[BijectionAuthState](/api/modules/react#bijectionauthstate) to descendants of this component.

Use this to integrate any auth provider with Bijection. The `useAuth` prop
should be a React hook that returns the provider's authentication state
and a function to fetch a JWT access token.

If the `useAuth` prop function updates causing a rerender then auth state
will transition to loading and the `fetchAccessToken()` function called again.

See [Custom Auth Integration](/auth/advanced/custom-auth) for more information.

#### Parameters

| Name | Type |
| :- | :- |
| `«destructured»` | `Object` |
| › `children?` | `ReactNode` |
| › `client` | `IBijectionReactClient` |
| › `useAuth` | () => \{ `isLoading`: `boolean` ; `isAuthenticated`: `boolean` ; `fetchAccessToken`: (`args`: \{ `forceRefreshToken`: `boolean`  }) => `Promise`\<`null` \| `string`>  } |

#### Returns

`Element`

***

### Authenticated

▸ **Authenticated**(`«destructured»`): `null` | `Element`

Renders children if the client is authenticated.

#### Parameters

| Name | Type |
| :- | :- |
| `«destructured»` | `Object` |
| › `children` | `ReactNode` |

#### Returns

`null` | `Element`

***

### Unauthenticated

▸ **Unauthenticated**(`«destructured»`): `null` | `Element`

Renders children if the client is using authentication but is not authenticated.

#### Parameters

| Name | Type |
| :- | :- |
| `«destructured»` | `Object` |
| › `children` | `ReactNode` |

#### Returns

`null` | `Element`

***

### AuthLoading

▸ **AuthLoading**(`«destructured»`): `null` | `Element`

Renders children if the client isn't using authentication or is in the process
of authenticating.

#### Parameters

| Name | Type |
| :- | :- |
| `«destructured»` | `Object` |
| › `children` | `ReactNode` |

#### Returns

`null` | `Element`

***

### AuthRefreshing

▸ **AuthRefreshing**(`«destructured»`): `null` | `Element`

Renders children while the client is refreshing the auth token for an
already-authenticated session (the server rejected the current token and
the socket is paused while a new one is fetched). Routine background
token rotation does not trigger this state.

Whether used inside of `<Authenticated>` or not, children will only be
rendered if the user is authenticated.

#### Parameters

| Name | Type |
| :- | :- |
| `«destructured»` | `Object` |
| › `children` | `ReactNode` |

#### Returns

`null` | `Element`

***

### useBijection

▸ **useBijection**(): [`BijectionReactClient`](/api/classes/react.BijectionReactClient)

Get the [BijectionReactClient](/api/classes/react.BijectionReactClient) within a React component.

This relies on the [BijectionProvider](/api/modules/react#bijectionprovider) being above in the React component tree.

#### Returns

[`BijectionReactClient`](/api/classes/react.BijectionReactClient)

The active [BijectionReactClient](/api/classes/react.BijectionReactClient) object, or `undefined`.

***

### BijectionProvider

▸ **BijectionProvider**(`props`): `null` | `ReactElement`\<`any`, `any`>

Provides an active Bijection [BijectionReactClient](/api/classes/react.BijectionReactClient) to descendants of this component.

Wrap your app in this component to use Bijection hooks `useQuery`,
`useMutation`, and `useBijection`.

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `props` | `Object` | an object with a `client` property that refers to a [BijectionReactClient](/api/classes/react.BijectionReactClient). |
| `props.client` | [`BijectionReactClient`](/api/classes/react.BijectionReactClient) | - |
| `props.children?` | `ReactNode` | - |

#### Returns

`null` | `ReactElement`\<`any`, `any`>

***

### useQuery

▸ **useQuery**\<`Query`>(`query`, `...args`): [`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`> | `undefined`

Load a reactive query within a React component.

This React hook subscribes to a Bijection query and causes a rerender whenever
the query result changes. The subscription is managed automatically --
it starts when the component mounts and stops when it unmounts.

Throws an error if not used under [BijectionProvider](/api/modules/react#bijectionprovider).

**`Example`**

```tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useQuery } from "bijection/react";
import { api } from "../bijection/_generated/api";

function TaskList() {
  // Reactively loads tasks, re-renders when data changes:
  const tasks = useQuery(api.tasks.list, { completed: false });

  // Returns `undefined` while loading:
  if (tasks === undefined) return <div>Loading...</div>;

  return tasks.map((task) => <div key={task._id}>{task.text}</div>);
}

// Pass "skip" to conditionally disable the query:
function MaybeProfile({ userId }: { userId?: Id<"users"> }) {
  const profile = useQuery(
    api.users.get,
    userId ? { userId } : "skip",
  );
  // ...
}
```

**`See`**

[https://docs.bijection.com/client/react#fetching-data](/client/react/overview#fetching-data)

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`"query"`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`"query"`> |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `query` | `Query` | a [FunctionReference](/api/modules/server#functionreference) for the public query to run like `api.dir1.dir2.filename.func`. |
| `...args` | [`OptionalRestArgsOrSkip`](/api/modules/react#optionalrestargsorskip)\<`Query`> | The arguments to the query function or the string `"skip"` if the query should not be loaded. |

#### Returns

[`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`> | `undefined`

the result of the query. Returns `undefined` while loading.

***

### useQuery\_experimental

▸ **useQuery\_experimental**\<`Query`, `ThrowOnError`>(`options`): [`UseQueryResult`](/api/modules/react#usequeryresult)\<[`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`>, `ThrowOnError`>

Load a reactive query within a React component using an options object.

This is an experimental form of [useQuery](/api/modules/react#usequery) that accepts a single
UseQueryOptions object instead of positional arguments.

Consumers are expected to check the returned object `status` field to
make proper use of the result. If an error occurs, it will be present
in the result object unless `throwOnError` is `true`, in which case
the error will be thrown instead.

**`Example`**

```tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useQuery_experimental as useQuery } from "bijection/react";
import { api } from "../bijection/_generated/api";

function TaskList() {
  const state = useQuery({ query: api.tasks.list, args: { completed: false } });

  if (state.status === "pending") return <div>Loading...</div>;
  if (state.status === "error") return <div>Error: {state.error.message}</div>;
  return state.data.map((task) => <div key={task._id}>{task.text}</div>);
}
```

**`See`**

[https://docs.bijection.com/client/react#fetching-data](/client/react/overview#fetching-data)

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`"query"`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`"query"`> |
| `ThrowOnError` | extends `boolean` = `false` |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `options` | `UseQueryOptions`\<`Query`, `ThrowOnError`> | Query options. Pass `args: "skip"` to disable the query. |

#### Returns

[`UseQueryResult`](/api/modules/react#usequeryresult)\<[`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`>, `ThrowOnError`>

the current query state as a [UseQueryResult](/api/modules/react#usequeryresult) object.

***

### useMutation

▸ **useMutation**\<`Mutation`>(`mutation`): [`ReactMutation`](/api/interfaces/react.ReactMutation)\<`Mutation`>

Construct a new [ReactMutation](/api/interfaces/react.ReactMutation).

Returns a function that you can call to execute a Bijection mutation. The
returned function is stable across renders (same reference identity), so
it can be safely used in dependency arrays and memoization.

Mutations can optionally be configured with
[optimistic updates](/client/react/optimistic-updates)
for instant UI feedback.

Throws an error if not used under [BijectionProvider](/api/modules/react#bijectionprovider).

**`Example`**

```tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useMutation } from "bijection/react";
import { api } from "../bijection/_generated/api";

function CreateTask() {
  const createTask = useMutation(api.tasks.create);

  const handleClick = async () => {
    await createTask({ text: "New task" });
  };

  return <button onClick={handleClick}>Add Task</button>;
}
```

**`See`**

[https://docs.bijection.com/client/react#editing-data](/client/react/overview#editing-data)

#### Type parameters

| Name | Type |
| :- | :- |
| `Mutation` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`"mutation"`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`"mutation"`> |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `mutation` | `Mutation` | A [FunctionReference](/api/modules/server#functionreference) for the public mutation to run like `api.dir1.dir2.filename.func`. |

#### Returns

[`ReactMutation`](/api/interfaces/react.ReactMutation)\<`Mutation`>

The [ReactMutation](/api/interfaces/react.ReactMutation) object with that name.

***

### useAction

▸ **useAction**\<`Action`>(`action`): [`ReactAction`](/api/interfaces/react.ReactAction)\<`Action`>

Construct a new [ReactAction](/api/interfaces/react.ReactAction).

Returns a function that you can call to execute a Bijection action. Actions
can call third-party APIs and perform side effects. The returned function
is stable across renders (same reference identity).

**Error handling:** Actions can fail (e.g., if an external API is down).
Always wrap action calls in try/catch or handle the rejected promise.

**Note:** In most cases, calling an action directly from a client is an
anti-pattern. Prefer having the client call a mutation that captures the
user's intent (by writing to the database) and then schedules the action
via `ctx.scheduler.runAfter`. This ensures the intent is durably recorded
even if the client disconnects.

Throws an error if not used under [BijectionProvider](/api/modules/react#bijectionprovider).

**`Example`**

```tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useAction } from "bijection/react";
import { api } from "../bijection/_generated/api";

function GenerateSummary() {
  const generate = useAction(api.ai.generateSummary);

  const handleClick = async () => {
    try {
      const summary = await generate({ text: "Some long text..." });
      console.log(summary);
    } catch (error) {
      console.error("Action failed:", error);
    }
  };

  return <button onClick={handleClick}>Generate</button>;
}
```

**`See`**

[https://docs.bijection.com/functions/actions#calling-actions-from-clients](/functions/actions#calling-actions-from-clients)

#### Type parameters

| Name | Type |
| :- | :- |
| `Action` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`"action"`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`"action"`> |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `action` | `Action` | A [FunctionReference](/api/modules/server#functionreference) for the public action to run like `api.dir1.dir2.filename.func`. |

#### Returns

[`ReactAction`](/api/interfaces/react.ReactAction)\<`Action`>

The [ReactAction](/api/interfaces/react.ReactAction) object with that name.

***

### useBijectionConnectionState

▸ **useBijectionConnectionState**(): [`ConnectionState`](/api/modules/browser#connectionstate)

React hook to get the current [ConnectionState](/api/modules/browser#connectionstate) and subscribe to changes.

This hook returns the current connection state and automatically rerenders
when any part of the connection state changes (e.g., when going online/offline,
when requests start/complete, etc.).

The shape of ConnectionState may change in the future which may cause this
hook to rerender more frequently.

Throws an error if not used under [BijectionProvider](/api/modules/react#bijectionprovider).

#### Returns

[`ConnectionState`](/api/modules/browser#connectionstate)

The current [ConnectionState](/api/modules/browser#connectionstate) with the Bijection backend.

***

### usePreloadedQuery

▸ **usePreloadedQuery**\<`Query`>(`preloadedQuery`): [`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`>

Load a reactive query within a React component using a `Preloaded` payload
from a Server Component returned by [preloadQuery](/api/modules/nextjs#preloadquery).

This React hook contains internal state that will cause a rerender
whenever the query result changes.

Throws an error if not used under [BijectionProvider](/api/modules/react#bijectionprovider).

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`FunctionReference`](/api/modules/server#functionreference)\<`"query"`> \| [`FunctionReference_future`](/api/modules/server#functionreference_future)\<`"query"`> |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `preloadedQuery` | [`Preloaded`](/api/modules/react#preloaded)\<`Query`> | The `Preloaded` query payload from a Server Component. |

#### Returns

[`FunctionReturnType`](/api/modules/server#functionreturntype)\<`Query`>

the result of the query. Initially returns the result fetched
by the Server Component. Subsequently returns the result fetched by the client.

***

### usePaginatedQuery

▸ **usePaginatedQuery**\<`Query`>(`query`, `args`, `options`): [`UsePaginatedQueryReturnType`](/api/modules/react#usepaginatedqueryreturntype)\<`Query`>

Load data reactively from a paginated query to a create a growing list.

This can be used to power "infinite scroll" UIs.

This hook must be used with public query references that match
[PaginatedQueryReference](/api/modules/react#paginatedqueryreference).

`usePaginatedQuery` concatenates all the pages of results into a single list
and manages the continuation cursors when requesting more items.

Example usage:

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const { results, status, isLoading, loadMore } = usePaginatedQuery(
  api.messages.list,
  { channel: "#general" },
  { initialNumItems: 5 }
);
```

If the query reference or arguments change, the pagination state will be reset
to the first page. Similarly, if any of the pages result in an InvalidCursor
error or an error associated with too much data, the pagination state will also
reset to the first page.

To learn more about pagination, see [Paginated Queries](/database/pagination).

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `query` | `Query` | A FunctionReference to the public query function to run. |
| `args` | `"skip"` \| [`Expand`](/api/modules/server#expand)\<[`BetterOmit`](/api/modules/server#betteromit)\<[`FunctionArgs`](/api/modules/server#functionargs)\<`Query`>, `"paginationOpts"`>> | The arguments object for the query function, excluding the `paginationOpts` property. That property is injected by this hook. |
| `options` | `Object` | An object specifying the `initialNumItems` to be loaded in the first page. |
| `options.initialNumItems` | `number` | - |

#### Returns

[`UsePaginatedQueryReturnType`](/api/modules/react#usepaginatedqueryreturntype)\<`Query`>

A [UsePaginatedQueryResult](/api/modules/react#usepaginatedqueryresult) that includes the currently loaded
items, the status of the pagination, and a `loadMore` function.

***

### resetPaginationId

▸ **resetPaginationId**(): `void`

Reset pagination id for tests only, so tests know what it is.

#### Returns

`void`

***

### optimisticallyUpdateValueInPaginatedQuery

▸ **optimisticallyUpdateValueInPaginatedQuery**\<`Query`>(`localStore`, `query`, `args`, `updateValue`): `void`

Optimistically update the values in a paginated list.

This optimistic update is designed to be used to update data loaded with
[usePaginatedQuery](/api/modules/react#usepaginatedquery). It updates the list by applying
`updateValue` to each element of the list across all of the loaded pages.

This will only apply to queries with a matching names and arguments.

Example usage:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const myMutation = useMutation(api.myModule.myMutation)
.withOptimisticUpdate((localStore, mutationArg) => {

  // Optimistically update the document with ID `mutationArg`
  // to have an additional property.

  optimisticallyUpdateValueInPaginatedQuery(
    localStore,
    api.myModule.paginatedQuery
    {},
    currentValue => {
      if (mutationArg === currentValue._id) {
        return {
          ...currentValue,
          "newProperty": "newValue",
        };
      }
      return currentValue;
    }
  );

});
```

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `localStore` | [`OptimisticLocalStore`](/api/interfaces/browser.OptimisticLocalStore) | An [OptimisticLocalStore](/api/interfaces/browser.OptimisticLocalStore) to update. |
| `query` | `Query` | A [FunctionReference](/api/modules/server#functionreference) for the paginated query to update. |
| `args` | [`Expand`](/api/modules/server#expand)\<[`BetterOmit`](/api/modules/server#betteromit)\<[`FunctionArgs`](/api/modules/server#functionargs)\<`Query`>, `"paginationOpts"`>> | The arguments object to the query function, excluding the `paginationOpts` property. |
| `updateValue` | (`currentValue`: [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`>) => [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`> | A function to produce the new values. |

#### Returns

`void`

***

### insertAtTop

▸ **insertAtTop**\<`Query`>(`options`): `void`

Updates a paginated query to insert an element at the top of the list.

This is regardless of the sort order, so if the list is in descending order,
the inserted element will be treated as the "biggest" element, but if it's
ascending, it'll be treated as the "smallest".

Example:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const createTask = useMutation(api.tasks.create)
  .withOptimisticUpdate((localStore, mutationArgs) => {
  insertAtTop({
    paginatedQuery: api.tasks.list,
    argsToMatch: { listId: mutationArgs.listId },
    localQueryStore: localStore,
    item: { _id: crypto.randomUUID() as Id<"tasks">, title: mutationArgs.title, completed: false },
  });
});
```

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `options` | `Object` | - |
| `options.paginatedQuery` | `Query` | A function reference to the paginated query. |
| `options.argsToMatch?` | `Partial`\<[`Expand`](/api/modules/server#expand)\<[`BetterOmit`](/api/modules/server#betteromit)\<[`FunctionArgs`](/api/modules/server#functionargs)\<`Query`>, `"paginationOpts"`>>> | Optional arguments that must be in each relevant paginated query. This is useful if you use the same query function with different arguments to load different lists. |
| `options.localQueryStore` | [`OptimisticLocalStore`](/api/interfaces/browser.OptimisticLocalStore) | |
| `options.item` | [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`> | The item to insert. |

#### Returns

`void`

***

### insertAtBottomIfLoaded

▸ **insertAtBottomIfLoaded**\<`Query`>(`options`): `void`

Updates a paginated query to insert an element at the bottom of the list.

This is regardless of the sort order, so if the list is in descending order,
the inserted element will be treated as the "smallest" element, but if it's
ascending, it'll be treated as the "biggest".

This only has an effect if the last page is loaded, since otherwise it would result
in the element being inserted at the end of whatever is loaded (which is the middle of the list)
and then popping out once the optimistic update is over.

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `options` | `Object` | - |
| `options.paginatedQuery` | `Query` | A function reference to the paginated query. |
| `options.argsToMatch?` | `Partial`\<[`Expand`](/api/modules/server#expand)\<[`BetterOmit`](/api/modules/server#betteromit)\<[`FunctionArgs`](/api/modules/server#functionargs)\<`Query`>, `"paginationOpts"`>>> | Optional arguments that must be in each relevant paginated query. This is useful if you use the same query function with different arguments to load different lists. |
| `options.localQueryStore` | [`OptimisticLocalStore`](/api/interfaces/browser.OptimisticLocalStore) | |
| `options.item` | [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`> | - |

#### Returns

`void`

***

### insertAtPosition

▸ **insertAtPosition**\<`Query`>(`options`): `void`

This is a helper function for inserting an item at a specific position in a paginated query.

You must provide the sortOrder and a function for deriving the sort key (an array of values) from an item in the list.

This will only work if the server query uses the same sort order and sort key as the optimistic update.

Example:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const createTask = useMutation(api.tasks.create)
  .withOptimisticUpdate((localStore, mutationArgs) => {
  insertAtPosition({
    paginatedQuery: api.tasks.listByPriority,
    argsToMatch: { listId: mutationArgs.listId },
    sortOrder: "asc",
    sortKeyFromItem: (item) => [item.priority, item._creationTime],
    localQueryStore: localStore,
    item: {
      _id: crypto.randomUUID() as Id<"tasks">,
      _creationTime: Date.now(),
      title: mutationArgs.title,
      completed: false,
      priority: mutationArgs.priority,
    },
  });
});
```

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `options` | `Object` | - |
| `options.paginatedQuery` | `Query` | A function reference to the paginated query. |
| `options.argsToMatch?` | `Partial`\<[`Expand`](/api/modules/server#expand)\<[`BetterOmit`](/api/modules/server#betteromit)\<[`FunctionArgs`](/api/modules/server#functionargs)\<`Query`>, `"paginationOpts"`>>> | Optional arguments that must be in each relevant paginated query. This is useful if you use the same query function with different arguments to load different lists. |
| `options.sortOrder` | `"asc"` \| `"desc"` | The sort order of the paginated query ("asc" or "desc"). |
| `options.sortKeyFromItem` | (`element`: [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`>) => [`Value`](/api/modules/values#value) \| [`Value`](/api/modules/values#value)\[] | A function for deriving the sort key (an array of values) from an element in the list. Including a tie-breaker field like `_creationTime` is recommended. |
| `options.localQueryStore` | [`OptimisticLocalStore`](/api/interfaces/browser.OptimisticLocalStore) | |
| `options.item` | [`PaginatedQueryItem`](/api/modules/react#paginatedqueryitem)\<`Query`> | The item to insert. |

#### Returns

`void`

***

### usePaginatedQuery\_experimental

▸ **usePaginatedQuery\_experimental**\<`Query`>(`query`, `args`, `options`): [`UsePaginatedQueryReturnType`](/api/modules/react#usepaginatedqueryreturntype)\<`Query`>

Experimental new usePaginatedQuery implementation that will replace the current one
in the future.

Load data reactively from a paginated query to a create a growing list.

This is an alternate implementation that relies on new client pagination logic.

This can be used to power "infinite scroll" UIs.

This hook must be used with public query references that match
[PaginatedQueryReference](/api/modules/react#paginatedqueryreference).

`usePaginatedQuery` concatenates all the pages of results into a single list
and manages the continuation cursors when requesting more items.

Example usage:

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const { results, status, isLoading, loadMore } = usePaginatedQuery(
  api.messages.list,
  { channel: "#general" },
  { initialNumItems: 5 }
);
```

If the query reference or arguments change, the pagination state will be reset
to the first page. Similarly, if any of the pages result in an InvalidCursor
error or an error associated with too much data, the pagination state will also
reset to the first page.

To learn more about pagination, see [Paginated Queries](/database/pagination).

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `query` | `Query` | A FunctionReference to the public query function to run. |
| `args` | `"skip"` \| [`PaginatedQueryArgs`](/api/modules/react#paginatedqueryargs)\<`Query`> | The arguments object for the query function, excluding the `paginationOpts` property. That property is injected by this hook. |
| `options` | `Object` | An object specifying the `initialNumItems` to be loaded in the first page. |
| `options.initialNumItems` | `number` | - |

#### Returns

[`UsePaginatedQueryReturnType`](/api/modules/react#usepaginatedqueryreturntype)\<`Query`>

A [UsePaginatedQueryResult](/api/modules/react#usepaginatedqueryresult) that includes the currently loaded
items, the status of the pagination, and a `loadMore` function.

▸ **usePaginatedQuery\_experimental**\<`Query`, `ThrowOnError`>(`options`): [`UsePaginatedQueryObjectReturnType`](/api/modules/react#usepaginatedqueryobjectreturntype)\<`Query`, `ThrowOnError`>

Experimental new usePaginatedQuery implementation that accepts an options object
rather than positional arguments.

#### Type parameters

| Name | Type |
| :- | :- |
| `Query` | extends [`PaginatedQueryReference`](/api/modules/react#paginatedqueryreference) |
| `ThrowOnError` | extends `boolean` = `false` |

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `options` | [`UsePaginatedQueryOptions`](/api/modules/react#usepaginatedqueryoptions)\<`Query`, `ThrowOnError`> | A [UsePaginatedQueryOptions](/api/modules/react#usepaginatedqueryoptions) object including `query` and `args`. |

#### Returns

[`UsePaginatedQueryObjectReturnType`](/api/modules/react#usepaginatedqueryobjectreturntype)\<`Query`, `ThrowOnError`>

A [UsePaginatedQueryObjectReturnType](/api/modules/react#usepaginatedqueryobjectreturntype) object with `data`, `status`,
`canLoadMore`, `isLoading`, `error`, and `loadMore`. `status` is `"pending"` while
loading, `"success"` when data is available, or `"error"` if the query threw.
When `throwOnError` is `true`, the `"error"` status is excluded from the return
type since errors will be thrown instead.
`canLoadMore` is `true` only when idle and more pages exist.

***

### useQueries

▸ **useQueries**(`queries`): `Record`\<`string`, `any` | `undefined` | `Error`>

Load a variable number of reactive Bijection queries.

`useQueries` is similar to [useQuery](/api/modules/react#usequery) but it allows
loading multiple queries which can be useful for loading a dynamic number
of queries without violating the rules of React hooks.

This hook accepts an object whose keys are identifiers for each query and the
values are objects of
`{ query: FunctionReference | FunctionReference_future, args: Record<string, Value> }`.
The `query` is a reference to the Bijection query function to load, and the
`args` are the arguments to that function.

The hook returns an object that maps each identifier to the result of the query,
`undefined` if the query is still loading, or an instance of `Error` if the query
threw an exception.

For example if you loaded a query like:

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const results = useQueries({
  messagesInGeneral: {
    query: "listMessages",
    args: { channel: "#general" }
  }
});
```

then the result would look like:

```typescript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
{
  messagesInGeneral: [{
    channel: "#general",
    body: "hello"
    _id: ...,
    _creationTime: ...
  }]
}
```

This React hook contains internal state that will cause a rerender
whenever any of the query results change.

Throws an error if not used under [BijectionProvider](/api/modules/react#bijectionprovider).

#### Parameters

| Name | Type | Description |
| :- | :- | :- |
| `queries` | `RequestForQueriesCompat` | An object mapping identifiers to objects of `{query: string, args: Record<string, Value> }` describing which query functions to fetch. |

#### Returns

`Record`\<`string`, `any` | `undefined` | `Error`>

An object with the same keys as the input. The values are the result
of the query function, `undefined` if it's still loading, or an `Error` if
it threw an exception.
