Skip to main content

Module: react

Tools to integrate Convex into React applications.

This module contains:

  1. ConvexReactClient, a client for using Convex in React.
  2. ConvexProvider, a component that stores this client in React context.
  3. Authenticated, Unauthenticated and AuthLoading helper auth components.
  4. Hooks useQuery, useMutation, useAction and more for accessing this client from your React components.

Usage

Creating the client

import { ConvexReactClient } from "convex/react";

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

Storing the client in React Context

import { ConvexProvider } from "convex/react";

<ConvexProvider client={convex}>
<App />
</ConvexProvider>

Using the auth helpers

import { Authenticated, Unauthenticated, AuthLoading } from "convex/react";

<Authenticated>
Logged in
</Authenticated>
<Unauthenticated>
Logged out
</Unauthenticated>
<AuthLoading>
Still loading
</AuthLoading>

Using React hooks

import { useQuery, useMutation } from "convex/react";
import { api } from "../convex/_generated/api";

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

Classes

Interfaces

Type Aliases

AuthTokenFetcher

Ƭ AuthTokenFetcher: (args: { forceRefreshToken: boolean }) => Promise<string | null | undefined>

Type declaration

▸ (args): Promise<string | null | undefined>

An async function returning the JWT-encoded OpenID Connect Identity Token if available.

forceRefreshToken is true if the server rejected a previously returned token, and the client should try to fetch a new one.

See setAuth.

Parameters
NameType
argsObject
args.forceRefreshTokenboolean
Returns

Promise<string | null | undefined>

Defined in

browser/sync/authentication_manager.ts:21


ConvexAuthState

Ƭ ConvexAuthState: Object

Type representing the state of an auth integration with Convex.

Type declaration

NameType
isLoadingboolean
isAuthenticatedboolean

Defined in

react/ConvexAuthState.tsx:26


OptionalRestArgsOrSkip

Ƭ OptionalRestArgsOrSkip<FuncRef>: FuncRef["_args"] extends EmptyObject ? [args?: EmptyObject | "skip"] : [args: FuncRef["_args"] | "skip"]

Type parameters

NameType
FuncRefextends FunctionReference<any>

Defined in

react/client.ts:575


Preloaded

Ƭ Preloaded<Query>: Object

The preloaded query payload, which should be passed to a client component and passed to usePreloadedQuery.

Type parameters

NameType
Queryextends FunctionReference<"query">

Type declaration

NameType
__typeQuery
_namestring
_argsJSONstring
_valueJSONstring

Defined in

react/hydration.tsx:12


PaginatedQueryReference

Ƭ PaginatedQueryReference: FunctionReference<"query", "public", { paginationOpts: PaginationOptions }, PaginationResult<any>>

A FunctionReference that is usable with usePaginatedQuery.

This function reference must:

Defined in

react/use_paginated_query.ts:30


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

Defined in

react/use_paginated_query.ts:440


PaginationStatus

Ƭ PaginationStatus: UsePaginatedQueryResult<any>["status"]

The possible pagination statuses in UsePaginatedQueryResult.

This is a union of string literal types.

Defined in

react/use_paginated_query.ts:468


PaginatedQueryArgs

Ƭ PaginatedQueryArgs<Query>: Expand<BetterOmit<FunctionArgs<Query>, "paginationOpts">>

Given a PaginatedQueryReference, get the type of the arguments object for the query, excluding the paginationOpts argument.

Type parameters

NameType
Queryextends PaginatedQueryReference

Defined in

react/use_paginated_query.ts:476


PaginatedQueryItem

Ƭ PaginatedQueryItem<Query>: FunctionReturnType<Query>["page"][number]

Given a PaginatedQueryReference, get the type of the item being paginated over.

Type parameters

NameType
Queryextends PaginatedQueryReference

Defined in

react/use_paginated_query.ts:485


UsePaginatedQueryReturnType

Ƭ UsePaginatedQueryReturnType<Query>: UsePaginatedQueryResult<PaginatedQueryItem<Query>>

The return type of usePaginatedQuery.

Type parameters

NameType
Queryextends PaginatedQueryReference

Defined in

react/use_paginated_query.ts:493


RequestForQueries

Ƭ RequestForQueries: Record<string, { query: FunctionReference<"query"> ; args: Record<string, 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.

Defined in

react/use_queries.ts:126

Functions

useConvexAuth

useConvexAuth(): Object

Get the ConvexAuthState within a React component.

This relies on a Convex auth integration provider being above in the React component tree.

Returns

Object

The current ConvexAuthState.

NameType
isLoadingboolean
isAuthenticatedboolean

Defined in

react/ConvexAuthState.tsx:43


ConvexProviderWithAuth

ConvexProviderWithAuth(«destructured»): Element

A replacement for ConvexProvider which additionally provides ConvexAuthState to descendants of this component.

Use this to integrate any auth provider with Convex. 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 wil transition to loading and the fetchAccessToken() function called again.

See Custom Auth Integration for more information.

Parameters

NameType
«destructured»Object
› children?ReactNode
› clientIConvexReactClient
› useAuth() => { isLoading: boolean ; isAuthenticated: boolean ; fetchAccessToken: (args: { forceRefreshToken: boolean }) => Promise<null | string> }

Returns

Element

Defined in

react/ConvexAuthState.tsx:75


Authenticated

Authenticated(«destructured»): null | Element

Renders children if the client is authenticated.

Parameters

NameType
«destructured»Object
› childrenReactNode

Returns

null | Element

Defined in

react/auth_helpers.tsx:10


Unauthenticated

Unauthenticated(«destructured»): null | Element

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

Parameters

NameType
«destructured»Object
› childrenReactNode

Returns

null | Element

Defined in

react/auth_helpers.tsx:23


AuthLoading

AuthLoading(«destructured»): null | Element

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

Parameters

NameType
«destructured»Object
› childrenReactNode

Returns

null | Element

Defined in

react/auth_helpers.tsx:37


useConvex

useConvex(): ConvexReactClient

Get the ConvexReactClient within a React component.

This relies on the ConvexProvider being above in the React component tree.

Returns

ConvexReactClient

The active ConvexReactClient object, or undefined.

Defined in

react/client.ts:550


ConvexProvider

ConvexProvider(props, deprecatedLegacyContext?): null | ReactElement<any, any>

Provides an active Convex ConvexReactClient to descendants of this component.

Wrap your app in this component to use Convex hooks useQuery, useMutation, and useConvex.

Parameters

NameTypeDescription
propsObjectan object with a client property that refers to a ConvexReactClient.
props.clientConvexReactClient-
props.children?ReactNode-
deprecatedLegacyContext?anyDeprecated See React Docs

Returns

null | ReactElement<any, any>

Defined in

../../common/temp/node_modules/.pnpm/@types+react@18.3.5/node_modules/@types/react/ts5.0/index.d.ts:1115


useQuery

useQuery<Query>(query, ...args): Query["_returnType"] | undefined

Load a reactive query within a React component.

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

Throws an error if not used under ConvexProvider.

Type parameters

NameType
Queryextends FunctionReference<"query">

Parameters

NameTypeDescription
queryQuerya FunctionReference for the public query to run like api.dir1.dir2.filename.func.
...argsOptionalRestArgsOrSkip<Query>The arguments to the query function or the string "skip" if the query should not be loaded.

Returns

Query["_returnType"] | undefined

the result of the query. If the query is loading returns undefined.

Defined in

react/client.ts:596


useMutation

useMutation<Mutation>(mutation): ReactMutation<Mutation>

Construct a new ReactMutation.

Mutation objects can be called like functions to request execution of the corresponding Convex function, or further configured with optimistic updates.

The value returned by this hook is stable across renders, so it can be used by React dependency arrays and memoization logic relying on object identity without causing rerenders.

Throws an error if not used under ConvexProvider.

Type parameters

NameType
Mutationextends FunctionReference<"mutation">

Parameters

NameTypeDescription
mutationMutationA FunctionReference for the public mutation to run like api.dir1.dir2.filename.func.

Returns

ReactMutation<Mutation>

The ReactMutation object with that name.

Defined in

react/client.ts:648


useAction

useAction<Action>(action): ReactAction<Action>

Construct a new ReactAction.

Action objects can be called like functions to request execution of the corresponding Convex function.

The value returned by this hook is stable across renders, so it can be used by React dependency arrays and memoization logic relying on object identity without causing rerenders.

Throws an error if not used under ConvexProvider.

Type parameters

NameType
Actionextends FunctionReference<"action">

Parameters

NameTypeDescription
actionActionA FunctionReference for the public action to run like api.dir1.dir2.filename.func.

Returns

ReactAction<Action>

The ReactAction object with that name.

Defined in

react/client.ts:689


usePreloadedQuery

usePreloadedQuery<Query>(preloadedQuery): Query["_returnType"]

Load a reactive query within a React component using a Preloaded payload from a Server Component returned by preloadQuery.

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

Throws an error if not used under ConvexProvider.

Type parameters

NameType
Queryextends FunctionReference<"query">

Parameters

NameTypeDescription
preloadedQueryPreloaded<Query>The Preloaded query payload from a Server Component.

Returns

Query["_returnType"]

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

Defined in

react/hydration.tsx:34


usePaginatedQuery

usePaginatedQuery<Query>(query, args, options): 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.

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

Example usage:

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.

Type parameters

NameType
Queryextends PaginatedQueryReference

Parameters

NameTypeDescription
queryQueryA FunctionReference to the public query function to run.
args"skip" | Expand<BetterOmit<FunctionArgs<Query>, "paginationOpts">>The arguments object for the query function, excluding the paginationOpts property. That property is injected by this hook.
optionsObjectAn object specifying the initialNumItems to be loaded in the first page.
options.initialNumItemsnumber-

Returns

UsePaginatedQueryReturnType<Query>

A UsePaginatedQueryResult that includes the currently loaded items, the status of the pagination, and a loadMore function.

Defined in

react/use_paginated_query.ts:161


resetPaginationId

resetPaginationId(): void

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

Returns

void

Defined in

react/use_paginated_query.ts:419


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

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

NameType
Queryextends PaginatedQueryReference

Parameters

NameTypeDescription
localStoreOptimisticLocalStoreAn OptimisticLocalStore to update.
queryQueryA FunctionReference for the paginated query to update.
argsExpand<BetterOmit<FunctionArgs<Query>, "paginationOpts">>The arguments object to the query function, excluding the paginationOpts property.
updateValue(currentValue: PaginatedQueryItem<Query>) => PaginatedQueryItem<Query>A function to produce the new values.

Returns

void

Defined in

react/use_paginated_query.ts:539


useQueries

useQueries(queries): Record<string, any | undefined | Error>

Load a variable number of reactive Convex queries.

useQueries is similar to 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, args: Record<string, Value> }. The query is a FunctionReference for the Convex 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:

const results = useQueries({
messagesInGeneral: {
query: "listMessages",
args: { channel: "#general" }
}
});

then the result would look like:

{
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 ConvexProvider.

Parameters

NameTypeDescription
queriesRequestForQueriesAn 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.

Defined in

react/use_queries.ts:60