Skip to main content
← Guides

Guide

Expo SQLite vs WatermelonDB vs Realm 2026

Updated PkgPulse Team17 min read
0

Expo SQLite vs WatermelonDB vs Realm for React Native local databases in 2026. Offline sync, performance, lazy loading, TypeScript models, and which DB to use.

Contents

TL;DR

Choose Expo SQLite for explicit SQL and an Expo-supported local database. Choose WatermelonDB for observable models and a custom synchronization protocol. Evaluate Realm as a local object database with a community maintenance path. MongoDB ended Atlas Device Sync and its supported Device SDKs on September 30, 2025, so it is no longer a turnkey cloud-sync choice.

Key Takeaways

  • Expo SQLite exposes a database context — subscribe to changes and update React state explicitly.
  • WatermelonDB lazy loads — only fetches records you query, not entire tables
  • Realm uses objects — no SQL; realm.write() to mutate objects directly
  • WatermelonDB sync requires a backend — the client API is exported from @nozbe/watermelondb/sync.
  • Atlas Device Sync ended — evaluate a separate sync solution for Realm applications.
  • Expo SQLite supports WAL mode — write-ahead logging for concurrent reads + writes
  • All three are offline-first — data persists on device without network

Use Case Guide

Expo app, small-medium dataset        → Expo SQLite (zero config)
Productivity app (notes, todos)       → WatermelonDB (great DX + scale)
Large dataset (100k+ records)         → WatermelonDB (lazy evaluation)
Multi-device sync                     → A supported sync service or WatermelonDB + custom backend
Complex relational queries (JOINs)    → Expo SQLite (full SQL)
Reactive components                   → All three (different APIs)
TypeScript model definitions          → All three (Realm best typing)
No Expo (bare RN)                     → WatermelonDB or Realm

Expo SQLite (expo-sqlite v14+)

Install expo-sqlite using the Expo CLI. useSQLiteContext returns the database handle; change subscriptions and state updates are separate steps.

Installation

npx expo install expo-sqlite

Database Setup and Schema

// lib/database.ts
import * as SQLite from "expo-sqlite";

// Open database (creates if not exists)
export const db = SQLite.openDatabaseSync("myapp.db", { enableChangeListener: true });
// For standalone use, call await initDatabase(db) before queries.
// A SQLiteProvider should initialize the handle passed to onInit.

// Initialize schema (run on app start)
export async function initDatabase(db: SQLite.SQLiteDatabase) {
  // Enable WAL mode for better concurrent performance
  await db.execAsync("PRAGMA journal_mode = WAL;");
  await db.execAsync("PRAGMA foreign_keys = ON;");

  // Create tables
  await db.execAsync(`
    CREATE TABLE IF NOT EXISTS notes (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      content TEXT,
      created_at TEXT NOT NULL DEFAULT (datetime('now')),
      updated_at TEXT NOT NULL DEFAULT (datetime('now')),
      is_archived INTEGER NOT NULL DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS tags (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL UNIQUE
    );

    CREATE TABLE IF NOT EXISTS note_tags (
      note_id INTEGER REFERENCES notes(id) ON DELETE CASCADE,
      tag_id INTEGER REFERENCES tags(id) ON DELETE CASCADE,
      PRIMARY KEY (note_id, tag_id)
    );

    CREATE INDEX IF NOT EXISTS idx_notes_created_at ON notes(created_at);
    CREATE INDEX IF NOT EXISTS idx_notes_archived ON notes(is_archived);
  `);
}

CRUD Operations

import { db } from "./database";

interface Note {
  id: number;
  title: string;
  content: string | null;
  created_at: string;
  updated_at: string;
  is_archived: number; // SQLite stores this flag as 0 or 1.
}

// Insert
export async function createNote(title: string, content: string): Promise<number> {
  const result = await db.runAsync(
    "INSERT INTO notes (title, content) VALUES (?, ?)",
    [title, content]
  );
  return result.lastInsertRowId;
}

// Select all
export async function getAllNotes(): Promise<Note[]> {
  return await db.getAllAsync<Note>(
    "SELECT * FROM notes WHERE is_archived = 0 ORDER BY updated_at DESC"
  );
}

// Select one
export async function getNoteById(id: number): Promise<Note | null> {
  return await db.getFirstAsync<Note>(
    "SELECT * FROM notes WHERE id = ?",
    [id]
  );
}

// Update
export async function updateNote(id: number, title: string, content: string): Promise<void> {
  await db.runAsync(
    "UPDATE notes SET title = ?, content = ?, updated_at = datetime('now') WHERE id = ?",
    [title, content, id]
  );
}

// Delete
export async function deleteNote(id: number): Promise<void> {
  await db.runAsync("DELETE FROM notes WHERE id = ?", [id]);
}

// Transaction — batch operations
export async function archiveAllNotes(): Promise<void> {
  await db.withTransactionAsync(async () => {
    await db.runAsync("UPDATE notes SET is_archived = 1");
    await db.runAsync("UPDATE notes SET updated_at = datetime('now')");
  });
}

Change subscriptions with React state

Enable change listeners on every connection that writes, including the CRUD handle above. Inserts, updates and deletes in this rowid table emit change events on enabled connections. Filter by databaseFilePath; databaseName identifies the SQLite schema, normally main, rather than the filename. These events are not transaction-commit notifications.

// components/NotesList.tsx
import { useSQLiteContext } from "expo-sqlite";
import { SQLiteProvider, addDatabaseChangeListener } from "expo-sqlite";
import { useEffect, useState } from "react";
import { initDatabase } from "../lib/database";

interface Note {
  id: number;
  title: string;
  updated_at: string;
}

// Wrap with SQLiteProvider in your app root
export function AppRoot() {
  return (
    <SQLiteProvider
      databaseName="myapp.db"
      options={{ enableChangeListener: true }}
      onInit={initDatabase}
    >
      <App />
    </SQLiteProvider>
  );
}

// Application excerpt: subscription reloads the query and updates state.
function NotesList() {
  const db = useSQLiteContext();

  // Context supplies a handle, not an automatically reactive query.
  const [notes, setNotes] = useState<Note[]>([]);

  useEffect(() => {
    async function loadNotes() {
      const result = await db.getAllAsync<Note>(
        "SELECT id, title, updated_at FROM notes WHERE is_archived = 0 ORDER BY updated_at DESC"
      );
      setNotes(result);
    }

    loadNotes();

    // Subscribe through the module API after enabling change events.
    const subscription = addDatabaseChangeListener(({ databaseFilePath, tableName }) => {
      if (databaseFilePath === db.databasePath && tableName === "notes") {
        loadNotes();
      }
    });

    return () => subscription.remove();
  }, [db]);

  return (
    <FlatList
      data={notes}
      keyExtractor={(item) => String(item.id)}
      renderItem={({ item }) => (
        <TouchableOpacity onPress={() => navigateTo(item.id)}>
          <Text>{item.title}</Text>
          <Text>{item.updated_at}</Text>
        </TouchableOpacity>
      )}
    />
  );
}
// Native FTS5 example. Run table/trigger creation and rebuild in a migration.
// Web builds need separately configured FTS support.
await db.execAsync(`
  CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(
    title, content,
    content='notes',
    content_rowid='id'
  );
  CREATE TRIGGER IF NOT EXISTS notes_ai AFTER INSERT ON notes BEGIN
    INSERT INTO notes_fts(rowid, title, content) VALUES (new.id, new.title, new.content);
  END;
  CREATE TRIGGER IF NOT EXISTS notes_ad AFTER DELETE ON notes BEGIN
    INSERT INTO notes_fts(notes_fts, rowid, title, content)
    VALUES ('delete', old.id, old.title, old.content);
  END;
  CREATE TRIGGER IF NOT EXISTS notes_au AFTER UPDATE ON notes BEGIN
    INSERT INTO notes_fts(notes_fts, rowid, title, content)
    VALUES ('delete', old.id, old.title, old.content);
    INSERT INTO notes_fts(rowid, title, content) VALUES (new.id, new.title, new.content);
  END;
  INSERT INTO notes_fts(notes_fts) VALUES ('rebuild');
`);

// Search
async function searchNotes(query: string): Promise<Note[]> {
  return await db.getAllAsync<Note>(`
    SELECT n.* FROM notes n
    JOIN notes_fts ON notes_fts.rowid = n.id
    WHERE notes_fts MATCH ?
    ORDER BY rank
  `, [query]);
}

WatermelonDB: High-Performance React Native Database

WatermelonDB uses lazy evaluation to avoid loading entire tables into memory — only records you actually render get fetched.

Installation

npm install @nozbe/watermelondb
 # withObservables is exported by the WatermelonDB React integration.
npx pod-install  # iOS

Model Definitions

// models/Note.ts
import { Model } from "@nozbe/watermelondb";
import { field, date, text } from "@nozbe/watermelondb/decorators";

export class Note extends Model {
  static table = "notes";

  @text("title") title!: string;
  @text("content") content!: string;
  @field("is_archived") isArchived!: boolean;
  @date("created_at") createdAt!: Date;
  @date("updated_at") updatedAt!: Date;
}
// models/schema.ts
import { appSchema, tableSchema } from "@nozbe/watermelondb/Schema";

export const schema = appSchema({
  version: 1,
  tables: [
    tableSchema({
      name: "notes",
      columns: [
        { name: "title", type: "string" },
        { name: "content", type: "string", isOptional: true },
        { name: "is_archived", type: "boolean" },
        { name: "created_at", type: "number" },
        { name: "updated_at", type: "number" },
      ],
    }),
  ],
});

Database Setup

// lib/database.ts
import { Database } from "@nozbe/watermelondb";
import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite";
import { schemaMigrations } from "@nozbe/watermelondb/Schema/migrations";
import { schema } from "../models/schema";
import { Note } from "../models/Note";

const adapter = new SQLiteAdapter({
  schema,
  migrations: schemaMigrations({ migrations: [] }), // Define migrations when schema changes
  jsi: true,        // JSI for better performance (requires Hermes)
  onSetUpError: (error) => {
    console.error("WatermelonDB setup error:", error);
  },
});

export const database = new Database({
  adapter,
  modelClasses: [Note],
});

CRUD Operations

// actions/noteActions.ts
import { database } from "../lib/database";
import { Note } from "../models/Note";

export async function createNote(title: string, content: string): Promise<Note> {
  return await database.write(async () => {
    return await database.get<Note>("notes").create((note) => {
      note.title = title;
      note.content = content;
      note.isArchived = false;
    });
  });
}

export async function updateNote(note: Note, updates: { title?: string; content?: string }): Promise<void> {
  await database.write(async () => {
    await note.update((n) => {
      if (updates.title !== undefined) n.title = updates.title;
      if (updates.content !== undefined) n.content = updates.content;
    });
  });
}

export async function deleteNote(note: Note): Promise<void> {
  await database.write(async () => {
    await note.markAsDeleted();  // Soft delete for sync compatibility
    // Or: await note.destroyPermanently();  // Hard delete
  });
}

Reactive Components with withObservables

import { withObservables } from "@nozbe/watermelondb/react";
import { database } from "../lib/database";
import { Note } from "../models/Note";
import { Q } from "@nozbe/watermelondb";

// Pure component that renders a list of notes
function NoteListComponent({ notes }: { notes: Note[] }) {
  return (
    <FlatList
      data={notes}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => <NoteItem note={item} />}
    />
  );
}

// Enhanced component — auto-subscribes to observable query
const NoteList = withObservables([], () => ({
  notes: database
    .get<Note>("notes")
    .query(Q.where("is_archived", false), Q.sortBy("updated_at", Q.desc))
    .observe(),  // Returns an Observable — re-renders when data changes
}))(NoteListComponent);

// Individual note component — also reactive
function NoteItemComponent({ note }: { note: Note }) {
  return (
    <View>
      <Text>{note.title}</Text>
      <Text>{note.content}</Text>
    </View>
  );
}

const NoteItem = withObservables(["note"], ({ note }: { note: Note }) => ({
  note: note.observe(),  // Re-renders when this specific note changes
}))(NoteItemComponent);

Realm: Local Object Database

Realm stores objects directly — no SQL, no tables-to-objects mapping. Atlas Device Sync is discontinued; local storage and any replacement synchronization must be evaluated separately.

Installation

npm install realm @realm/react
npx pod-install  # iOS

Schema Definition

// models/Note.ts
import Realm from "realm";

export class Note extends Realm.Object<Note> {
  _id!: Realm.BSON.ObjectId;
  title!: string;
  content!: string | null;
  isArchived!: boolean;
  createdAt!: Date;
  updatedAt!: Date;

  static schema: Realm.ObjectSchema = {
    name: "Note",
    primaryKey: "_id",
    properties: {
      _id: "objectId",
      title: "string",
      content: "string?",
      isArchived: { type: "bool", default: false },
      createdAt: "date",
      updatedAt: "date",
    },
  };
}

Setup (Local Mode)

// app/providers.tsx
import { RealmProvider } from "@realm/react";
import { Note } from "../models/Note";

export function AppProviders({ children }: { children: React.ReactNode }) {
  return (
    <RealmProvider schema={[Note]}>
      {children}
    </RealmProvider>
  );
}

CRUD Operations

import { useRealm, useQuery } from "@realm/react";
import Realm from "realm";
import { Note } from "../models/Note";

function NotesScreen() {
  const realm = useRealm();

  // Live query — re-renders when notes change
  const notes = useQuery(Note, (collection) =>
    collection.filtered("isArchived = false").sorted("updatedAt", true)
  );

  function createNote(title: string, content: string) {
    realm.write(() => {
      realm.create(Note, {
        _id: new Realm.BSON.ObjectId(),
        title,
        content,
        isArchived: false,
        createdAt: new Date(),
        updatedAt: new Date(),
      });
    });
  }

  function deleteNote(note: Note) {
    realm.write(() => {
      realm.delete(note);
    });
  }

  function archiveNote(note: Note) {
    realm.write(() => {
      note.isArchived = true;
      note.updatedAt = new Date();
    });
  }

  return (
    <View>
      <Button title="Add Note" onPress={() => createNote("New Note", "")} />
      <FlatList
        data={notes}
        keyExtractor={(item) => item._id.toString()}
        renderItem={({ item }) => (
          <TouchableOpacity onLongPress={() => deleteNote(item)}>
            <Text>{item.title}</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

Feature Comparison

FeatureExpo SQLiteWatermelonDBRealm
Query languageSQLWatermelon Query (JS)RealmQuery (JS)
Lazy loadingNoYes (core feature)Yes
React integrationuseSQLiteContext returns a handlewithObservables is a higher-order componentuseQuery subscribes to results
Change listeneraddDatabaseChangeListenerObservable queriesRealm collection listeners
RelationshipsYes (SQL JOINs)Yes (children/belongs_to)Yes (Object links)
MigrationsYes (Manual SQL)Yes (Schema migrations)Yes (Schema versioning)
Full-text searchYes (FTS5)NoYes
Cloud syncSeparate integrationCustom backend protocolAtlas Device Sync discontinued
Expo GoIncluded on supported platformsCustom native buildCustom native build
TypeScript modelsYes (generic types)Yes (Decorators)Yes (Realm.Object)
Large queriesBound result size with SQLQuery and observe required recordsQuery required objects
npm weekly~500k~100k~150k

Ecosystem and Community

Expo SQLite benefits from being part of the official Expo ecosystem. The documentation is maintained by the Expo team and stays current with every Expo SDK release. When breaking changes occur in React Native or the underlying SQLite implementation, the Expo team handles the compatibility layer. The Expo Discord is the best place for support, and issues on the expo/expo GitHub repository receive quick responses. The documented context, query and change-listener APIs provide the pieces for a reactive view; the application must connect them.

WatermelonDB has a dedicated community built around the Nozbe company, which uses it to power their own productivity apps in production. The GitHub repository is actively maintained, and the documentation covers advanced topics like sync protocol design, performance optimization, and schema migrations. The key community resource is the WatermelonDB GitHub Discussions board, where the maintainer Radek Pietruszewski has written extensively about database architecture patterns for React Native. The library's maturity is evident — it has been in production for years and handles large datasets at scale without surprises.

MongoDB ended the supported Atlas Device SDKs and Device Sync. The on-device database continues through open-source/community work. Check the React Native and local Realm release compatibility you need before choosing a maintenance path.

Real-World Adoption

Expo SQLite is the most commonly used local database in Expo-managed workflow projects. For apps in the Expo ecosystem building anything from a local workout tracker to a travel journal, expo-sqlite provides everything needed without leaving the managed workflow or dealing with native module installation. Change listeners can drive React state updates, but useSQLiteContext alone does not subscribe a view to query results. For React Native navigation patterns that work alongside these databases, see Expo Router vs React Navigation vs Solito.

WatermelonDB has strong adoption in productivity apps — note-taking apps, CRM tools, project management utilities — where the dataset grows over time and performance under hundreds of thousands of records matters. The Nozbe apps (Nozbe Personal, Nozbe Teams) are the primary showcase, demonstrating that WatermelonDB handles serious production workloads. The lazy evaluation model means that an app with 50,000 notes only loads the notes visible on screen, not the entire dataset.

Realm can provide local object storage and reactive queries. Existing applications that used Atlas Device Sync need a supported replacement or must remove sync. Do not use older Atlas pricing or authentication integration as a current reason to adopt Realm.

Performance Benchmarks

Performance differences between these libraries matter primarily at scale. This guide has no versioned mobile benchmark to establish a 50ms query limit or a record-count threshold for migration. Measure representative indexed queries, writes and device memory on the target hardware.

WatermelonDB fetches the records matched by a query. Displaying 20 rows does not by itself limit an unbounded query to 20 records. Expo SQLite would execute the SQL query, process all matching rows in SQLite, and return them to JavaScript — retaining a large unbounded result can exhaust memory on a device, but a well-indexed query returning 20 rows is fast. Realm's object-oriented model has a similar lazy-loading characteristic to WatermelonDB.

For write operations, WatermelonDB batches writes through a database.write() transaction, which amortizes the transaction overhead. Expo SQLite offers the same via withTransactionAsync. Bulk-insert speed depends on batching, indexes, runtime and device. No comparative result is claimed here. Realm's write performance is excellent because it bypasses the bridge with JSI in newer versions.

Migration and Getting Started

Starting with Expo SQLite is the lowest-friction path for a new Expo app. The setup is essentially a single npx expo install expo-sqlite and a schema initialization function. Teams coming from web development with SQLite or PostgreSQL experience will feel at home with the SQL API.

Migrating from Expo SQLite to WatermelonDB makes sense when measured query and UI behavior justify a model change, when reactive UI updates require significant boilerplate with the change listener pattern, or when you need to implement sync with a backend. The migration requires rewriting models as WatermelonDB classes and converting SQL queries to WatermelonDB's query API, which takes meaningful developer time.

When to Use Each

Choose Expo SQLite if:

  • Expo managed workflow (works in Expo Go)
  • Familiar with SQL — complex queries, JOINs, aggregations
  • Small to medium datasets (< 50k records) where lazy loading isn't critical
  • No sync requirements — pure on-device storage
  • Full-text search with FTS5

Choose WatermelonDB if:

  • Large datasets (notes apps, CRMs, inventory) where lazy loading is critical
  • Reactive React components that subscribe to query changes
  • Custom sync backend — a backend implementing WatermelonDB's required pull/push protocol
  • TypeScript model classes with @field, @text decorators
  • You can implement and operate the required synchronization backend

Choose Realm if:

  • Local object storage with a separately evaluated sync strategy
  • Object-oriented data model (no SQL/tables) is preferred
  • Strong MongoDB ecosystem integration
  • Full-text search without custom SQL setup
  • A maintenance plan based on the supported local/community package

Methodology

The examples use official Expo SQLite, WatermelonDB and local Realm documentation. Native snippets are application excerpts, not a tested device project. The FTS trigger pattern follows SQLite documentation. MongoDB's deprecation notice governs the discontinued sync claims.

Schema Migrations in Practice

All three databases support schema evolution, but the approaches differ significantly in how disruptive upgrades are for users.

Expo SQLite migrations are manual SQL scripts. You maintain a version number in a user_version PRAGMA and run sequential migration scripts on app startup. This is the same pattern used in server-side database migrations and is well-understood by developers familiar with tools like Flyway or Drizzle. The risk is that a bad migration on a user's device is difficult to roll back — the migration runs once, and if it fails partway through, you need careful error handling to avoid leaving the database in an inconsistent state. Always wrap migrations in transactions.

WatermelonDB's migration system is more structured. You define a schemaMigrations object containing versioned migrations with operations such as createTable and addColumns. WatermelonDB handles running the correct migrations for the current schema version and validates that migrations are complete. The downside is that WatermelonDB's migration DSL is not as flexible as raw SQL — complex data transformations require additional migration steps or writing custom migration functions.

Realm's schema versioning is the most automated of the three. You increment the schema version number, define a onMigration function if needed, and Realm handles running the migration on device. For simple additive changes (adding properties with default values), Realm can auto-migrate without any migration code. For property renames or type changes, you provide a migration callback. The schema validation at startup catches mismatches before any data corruption can occur.

Testing Local Databases in React Native

Testing code that relies on a local database requires special consideration in React Native. Expo SQLite and WatermelonDB use SQLite, while Realm uses its own database engine. Jest defaults to node from version 27. Choosing jsdom adds DOM APIs, not React Native database bindings; native integration tests still need a supported device or simulator environment.

For Expo SQLite, isolate application logic behind a database interface for unit tests. The documented web build uses WebAssembly and requires web setup; it is not a drop-in native module for Jest. Run native query and migration integration tests on a supported device or simulator.

WatermelonDB exposes a LokiJS adapter for JavaScript-based storage. The claimed @nozbe/watermelondb/adapters/memory package path is not a documented adapter. A test adapter does not replace integration tests against native SQLite.

For Realm, use the testing or mocking approach supported by the local Realm and React binding versions you install. The former @realm/testing recommendation was not verified and is removed. Mocked components do not validate database migrations or native bindings.

Related: Best JavaScript Testing Frameworks 2026, Best Node.js Background Job Libraries 2026, Supabase vs Firebase vs Appwrite BaaS 2026

Related: React Native MMKV vs AsyncStorage vs Expo SecureStore for key-value and secure storage that often complements a local database, or Expo EAS vs Fastlane vs Bitrise for CI/CD pipelines that build and test apps using these databases.

Source notes