Convex React
Convex React is the client library enabling your React application to interact with your Convex backend. It allows your frontend code to:
- Call your queries, mutations and actions
- Upload and display files from File Storage
- Authenticate users using Authentication
- Implement full text Search over your data
The Convex React client is open source and available on GitHub.
Follow the React Quickstart to get started with React using Vite.
Installation
Convex React is part of the convex
npm package:
npm install convex
Connecting to a backend
The ConvexReactClient
maintains a
connection to your Convex backend, and is used by the React hooks described
below to call your functions.
First you need to create an instance of the client by giving it your backend deployment URL. See Configuring Deployment URL on how to pass in the right value:
import { ConvexProvider, ConvexReactClient } from "convex/react";
const convex = new ConvexReactClient("https://<your domain here>.convex.cloud");
And then you make the client available to your app by passing it in to a
ConvexProvider
wrapping your component
tree:
reactDOMRoot.render(
<React.StrictMode>
<ConvexProvider client={convex}>
<App />
</ConvexProvider>
</React.StrictMode>,
);
Fetching data
Your React app fetches data using the useQuery
React hook by calling your queries via an
api
object.
The npx convex dev
command generates this api object for you in the
convex/_generated/api.js
module to provide better autocompletion in JavaScript
and end-to-end type safety in
TypeScript:
import { useQuery } from "convex/react";
import { api } from "../convex/_generated/api";
export function App() {
const data = useQuery(api.functions.myQuery);
return data ?? "Loading...";
}
The useQuery
hook returns undefined
while the data is first loading and
afterwards the return value of your query.
Query arguments
Arguments to your query follow the query name:
export function App() {
const a = "Hello world";
const b = 4;
const data = useQuery(api.functions.myQuery, { a, b });
//...
}
Reactivity
The useQuery
hook makes your app automatically reactive: when the underlying
data changes in your database, your component rerenders with the new query
result.
The first time the hook is used it creates a subscription to your backend for a given query and any arguments you pass in. When your component unmounts, the subscription is canceled.
Consistency
Convex React ensures that your application always renders a consistent view of the query results based on a single state of the underlying database.
Imagine a mutation changes some data in the database, and that 2 different
useQuery
call sites rely on this data. Your app will never render in an
inconsistent state where only one of the useQuery
call sites reflects the new
data.