Correct way to manage in React (Native)

In all the documentation I’ve read so far, a connection is opened, things are done, and then it is closed. What I’m wondering is, should the connection be opened and put in some sort of context, then reused for the lifetime of the running app? Or is the correct approach to do as needed, closing it directly after?

The way I have it, I have a database.ts file with essentially the following:

export const app = new Realm.App({ id: realmAppId })

let database: Realm | null = null

export const connect = async (shouldConnectAsync?: boolean) => {
  const config = {
    sync: {
      user: app.currentUser,

  database = shouldConnectAsync
    ? await
    : new Realm(config)

export const db = () => database

And then I use the exported db. For example db()?.write(() => { ... }). This may not be the best way to do it, and I kind of like your idea of using a React context to do this, but I think the point is pretty much the same: open it once and use that connection throughout the app.