Quick Start - React Native SDK
On this page
- About the @realm/react Package
- Set Up Your Realm App
- Define Object Models
- Configure a Realm
- Work With Realm Objects
- Find, Sort, and Filter Objects
- Create, Modify, and Delete Realm Objects
- Add Atlas Device Sync (Optional)
- Prerequisites
- Configure and Access a Synced Realm
- Next: Check out the Template Apps and Tutorial
This page demonstrates how to use Realm using the React Native SDK.
Before you begin, install the Realm React Native SDK.
About the @realm/react Package
@realm/react is a package used in the React Native SDK. It provides state-aware React hooks for Realm data. The hooks watch the Realm data and re-render components as needed.
The React Native SDK documentation uses the @realm/react
npm package for examples and describing concepts.
Set Up Your Realm App
After installing the realm
and @realm/react
packages, there are a
few more things to set up before you can access your realm and work with local
data:
Define your object models
Configure a realm by creating a realm context object, extracting hooks, and setting up providers
Define Object Models
Your application's object models define the data types that you can store within a realm. Each object model becomes a Realm object type.
To define a Realm object model:
Create a class that extends Realm.Object. For TypeScript, include the class name as a type. This lets you use the class with other Realm SDK methods that accept
Realm.Object
types.Add a
schema
field.For the
schema
value, create an object that containsproperties
andname
properties. The name value must be unique among object types in a Realm object model.
To learn more, refer to Define a Realm Object Model.
Configure a Realm
Before you can work with data, you need to configure a realm. This means you need
to set up context and providers from @realm/react
. To learn more, refer to
Configure a Realm.
To configure and access a local realm:
Import
createRealmContext()
from@realm/react
.Create a realm Configuration object. You must include your Realm object models in the
schema
property. You can also include optional configuration properties, like making the realm read only or adding Atlas Device Sync.Create a realm context with
createRealmContext()
. A realm context is a React Context object that contains React providers and hooks for working with your realm.Expose a realm with
RealmProvider
. To expose a realm, you need a realm context. From that context, extractRealmProvider
, which contains your realm's context.
Work With Realm Objects
After you have a data model and a configured realm, you can create, read, update, or delete Realm objects.
You must nest any components that perform these operations inside of a
RealmProvider
. The useRealm()
, useQuery()
, and useObject()
hooks
enable you to perform read and write operations in your realm.
Find, Sort, and Filter Objects
@realm/react
provides hooks to help you find a collection of Realm objects
or a single Realm object.
useQuery()
: TakesRealm.Object
type as argument. Returns Realm.Results with all objects in the realm for the type that you pass to it.useObject()
. TakesRealm.Object
type and primary key as arguments. Returns the Realm object for the primary key that you pass to it.
After finding a collection, you can filter or sort the results using Realm Query Language (RQL).
To learn more, refer to the Query Data.
Create, Modify, and Delete Realm Objects
After accessing the realm with useRealm()
, you can create, modify,
and delete objects inside of the realm in a Realm.write() transaction block.
To learn more, refer to Write Transactions.
Create Objects
To create a new Realm object, specify the object type, pass in the object's initial values, and add it to the realm in a write transaction block.
To learn more, refer to CRUD - Create.
Update Objects
To update a Realm Object, update its properties in a write transaction block.
To learn more, refer to CRUD - Update.
Delete Objects
To delete a Realm Object, call the Realm.delete() method in a write transaction block.
To learn more, refer to CRUD - Delete.
Add Atlas Device Sync (Optional)
After getting your local-only realm running, you can add Atlas Device Sync so that your realm's data can sync with a MongoDB Atlas cluster and other client devices.
To use Device Sync, you need to set up a couple more things:
Create a backend in Atlas App Services (see the prerequisites below)
Configure a Flexible Sync realm instead of a local-only realm
Prerequisites
Anonymous authentication enabled in the App Services UI
Flexible Sync enabled with Development Mode on
Configure and Access a Synced Realm
To configure and access a synced realm:
Initialize the App using
AppProvider
Authenticate a User with
UserProvider
Configure a Synced Realm with
RealmProvider
To learn more, refer to Configure a Synced Realm.
Initialize the App using AppProvider
To use App Services features, such as authentication and Device Sync, you must first access your App Services App using your App ID. You can find your App ID in the App Services UI.
import React from 'react'; import {AppProvider} from '@realm/react'; function AppWrapperSync() { return ( <AppProvider id={APP_ID}> <RestOfApp /> </AppProvider> ); }
Authenticate a User with UserProvider
Use the UserProvider
to handle sections of your app that need an authenticated user.
To authenticate and log in a user, provide a fallback
prop for UserProvider
.
This could be a log in screen component or a simple function that calls
App.logIn().
Users can only access the parts of your app nested within UserProvider
after they have authenticated. If there's no authenticated user,
the fallback
component renders and nested components do not.
import React from 'react'; import {useApp, AppProvider, UserProvider} from '@realm/react'; import {Button} from 'react-native'; function AppWrapperSync() { return ( <AppProvider id={APP_ID}> <UserProvider fallback={LogIn}> <RestOfApp /> </UserProvider> </AppProvider> ); } function LogIn() { const app = useApp(); async function logInUser() { // When anonymous authentication is enabled, users can immediately log // into your app without providing any identifying information. await app.logIn(Realm.Credentials.anonymous()); } return ( <Button title='Log In' onPress={logInUser} /> ); }
Configure a Synced Realm with RealmProvider
After you have initialized your App, authenticated a user, and defined your
object model, you can configure a synced realm. This is similar to configuring
a local realm. However, you need to add some additional props to the
RealmProvider
.
Create the realm's Configuration object. The Configuration object defines the parameters of a realm and identifies it. When creating a configuration object, make sure to pass your data models into the
schema
property.Create a realm context with
createRealmContext()
. A realm context is a React Context object that contains app-wide access to your realm.Extract the
RealmProvider
from the realm context, and then expose it to your app.Add the
sync
property toRealmProvider
and pass it a FlexibleSyncConfiguration object. This sync object must containflexible: true
.
You need at least one sync subscription before you can read or write synced data.
You can add subscriptions in your components or set up
initial subscriptions on
RealmProvider
.
The syntax to create, read, update, and delete objects in a synced realm is identical to the syntax for non-synced realms. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.
To learn more, refer to Configure a Synced Realm.
Next: Check out the Template Apps and Tutorial
If you are interested in a guided experience, you can read our Realm React Native SDK tutorial. This tutorial implements and expands on a base React Native app built with Realm and Device Sync.
You could also use the template app to experiment with the React Native SDK on your own. To set up the template app, refer to Template Apps in the Atlas App Services documentation.