React is a popular JavaScript library for building user interfaces. The SurrealDB SDK for JavaScript can be used in your React applications to interact with your SurrealDB instance.
This guide walks you through setting up a connection provider and executing queries in a React project.
Prerequisites
A basic understanding of React
A running SurrealDB instance
The JavaScript SDK installed in your project
Installing dependencies
In addition to surrealdb, this guide uses @tanstack/react-query to manage the asynchronous connection state. Install it alongside the SDK:
Follow the installation guide for more information on how to install the SDK in your project.
Creating the connection provider
We recommend initializing the SDK in a Context Provider so the Surreal client is accessible anywhere in your component tree. The provider below manages the connection lifecycle, tracks connection status via TanStack Query, and cleans up on unmount.
The params prop accepts the same options as .connect(), including namespace, database, and authentication.
Wrapping your application
In your top-level component, wrap the root with QueryClientProvider and SurrealProvider. Pass the endpoint and any connection options through the params prop.
Executing queries
Use the useSurrealClient() hook to access the Surreal instance from any component. All query methods are available on the client, including .query(), .select(), .create(), and more.
Handling authentication
You can build an authentication layer on top of the provider using the SDK's .signin() and .signup() methods. The example below shows a minimal hook for record access authentication.
Learn more
Connecting to SurrealDB for connection protocols and reconnection behavior
Authentication for signing in, signing up, and token management
Executing queries for query builders and raw SurrealQL
Live queries for real-time subscriptions
JavaScript SDK API reference for the complete method reference