Create-React-App Quickstart
Learn how to query data from Convex in a React app using Create React App.
Alternatively check out the React Quickstart using Vite.
- Create a React app
Create a React app using the
create-react-app
command.npx create-react-app my-app
- Install the Convex client and server library
To get started, install the
convex
package which provides a convenient interface for working with Convex from a React app.Navigate to your app directory and install
convex
.cd my-app && npm install convex
- Set up a Convex dev deployment
Next, run
npx convex dev
. This will prompt you to log in with GitHub, create a project, and save your production and deployment URLs.It will also create a
src/convex/
folder for you to write your backend API functions in. Thedev
command will then continue running to sync your functions with your dev deployment in the cloud.npx convex dev
- Create sample data for your database
In a new terminal window, create a
sampleData.jsonl
file with some sample data.sampleData.jsonl{"text": "Buy groceries", "isCompleted": true}
{"text": "Go for a swim", "isCompleted": true}
{"text": "Integrate Convex", "isCompleted": false} - Add the sample data to your database
Now that your project is ready, add a
tasks
table with the sample data into your Convex database with theimport
command.npx convex import --table tasks sampleData.jsonl
- Expose a database query
Add a new file
tasks.js
in thesrc/convex/
folder with a query function that loads the data.Exporting a query function from this file declares an API function named after the file and the export name,
api.tasks.get
.src/convex/tasks.jsimport { query } from "./_generated/server";
export const get = query({
args: {},
handler: async (ctx) => {
return await ctx.db.query("tasks").collect();
},
}); - Connect the app to your backend
In
index.js
, create aConvexReactClient
and pass it to aConvexProvider
wrapping your app.src/index.jsimport { ConvexProvider, ConvexReactClient } from "convex/react";
const convex = new ConvexReactClient(process.env.REACT_APP_CONVEX_URL);
root.render(
<React.StrictMode>
<ConvexProvider client={convex}>
<App />
</ConvexProvider>
</React.StrictMode>
); - Display the data in your app
In
App.js
, use theuseQuery
hook to fetch from yourapi.tasks.get
API function.src/App.jsimport { useQuery } from "convex/react";
import { api } from "./convex/_generated/api";
function App() {
const tasks = useQuery(api.tasks.get);
return (
<div className="App">
{JSON.stringify(tasks, null, 2)}
</div>
);
} - Start the app
Start the app, go to http://localhost:3000 in a browser, and see the serialized list of tasks at the top of the page.
npm start