ShipNative
PricingBlogFAQContact
Build my app
ShipNative
PricingBlogFAQContact
Build my app

Try ShipNative

Plan your app free

Describe it and get the plan and every screen designed. Building starts at $29/mo.

Build my app
Blog/Technical

Updated November 2026•9 min read

Building Offline-First React Native Apps

Saurabh Singh
Saurabh SinghFounder of ShipNative
An offline-first app treats the database on the phone as the source of truth. The network is a sync step that runs when it can. This guide covers the decisions that follow from that: which local store to use, how to detect connectivity, how to queue changes made offline and replay them, how to settle conflicts, and how to test all of it.

The short version

  1. Write locally. Save the change to the local database and add a row to the outbox in one transaction. The screen updates now.
  2. Notice the network. A connectivity listener tells you when a sync is worth trying.
  3. Replay the outbox. Send queued changes oldest first. Delete a row only after the server accepts it.
  4. Merge what comes back. Apply server rows to the local database with a conflict rule.

What offline-first means

In a network-first app, a button press sends a request and the screen waits for the answer. In an offline-first app, the button press writes to the local database and the screen updates at once. A separate step sends the change to the server later. Expo describes local-first the same way: the app reads and writes a database on the device, so it keeps working offline and syncs when it is connected.

This changes what you build. You need a local store, a list of changes that have not reached the server, a way to know when to try, and a rule for two edits to the same record. The next sections take them in that order.

Choose the local store

This site has a guide for each store. This table is only the decision. Open the guide for install steps and the API.

StoreWhat it isUse it forGuide
expo-sqliteA SQLite database that is persisted across app restarts. Runs in Expo Go.Records you list, filter or edit in groups, the outbox, anything that needs a transaction.Expo SQLite guide
react-native-mmkvKey-value storage with synchronous calls. Stores strings, booleans, numbers and ArrayBuffers, so objects must be turned into JSON strings first.Small values you read on every render: settings, a flag, the time of the last sync.MMKV guide
AsyncStorageAsynchronous, unencrypted, persistent key-value storage. Runs in Expo Go.Small data for a simple app. Move to SQLite when you need to query it.AsyncStorage guide

Sources: Expo SQLite, the react-native-mmkv README, and Expo AsyncStorage.

A practical split for a synced app: put the records in SQLite and the outbox in the same SQLite database, so both can be saved in one transaction. Keep small values, such as the time of the last sync, in MMKV or AsyncStorage.

If you would rather not write the sync yourself, the Expo guide lists libraries that include it, among them Legend-State, TinyBase, RxDB, Turso and PowerSync. It also warns that these tools are still early and that you may need to build a custom sync layer. Read the Expo local-first guide before you pick one.

Detect connectivity, but do not trust it

Two packages report network state. NetInfo (@react-native-community/netinfo) has NetInfo.fetch, NetInfo.addEventListener and the useNetInfo hook. expo-network has getNetworkStateAsync, useNetworkState and addNetworkStateListener. Both give you isConnected and isInternetReachable.

Neither field is a promise that a request will succeed. The Expo docs say isConnected does not mean the internet is reachable, and that on iOS isInternetReachable is always the same as isConnected. NetInfo says isInternetReachable is null when it is unknown. So treat the signal as a reason to try, not as proof.

import NetInfo from '@react-native-community/netinfo';

// Called soon after subscribing and on every change.
const unsubscribe = NetInfo.addEventListener((state) => {
  // isInternetReachable is null when unknown, so only skip a definite false.
  if (state.isConnected && state.isInternetReachable !== false) {
    drainOutbox();
  }
});

// Call unsubscribe() when the listener is no longer needed.

The listener only starts a sync. The sync itself must cope with a request that fails. That is the job of the outbox.

Queue writes in an outbox

The outbox is a table of changes the server has not accepted yet. Every local write adds one row in the same transaction as the data change. Expo suggests giving a network-dependent action a state such as queued, sending, accepted or failed, which maps onto the columns below.

Outbox stateMeaning
queuedSaved on the device, not sent yet.
sendingA request is in flight.
acceptedThe server confirmed it. Delete the outbox row.
failedThe server refused it for good. Show it to the user. Do not retry forever.

The sample below uses expo-sqlite: openDatabaseAsync, execAsync, runAsync, getAllAsync and withTransactionAsync. The Expo docs recommend enabling WAL journal mode when you create a database. The queue and merge logic is plain TypeScript.

import * as SQLite from 'expo-sqlite';

let dbPromise: Promise<SQLite.SQLiteDatabase> | null = null;

export function getDb() {
  if (!dbPromise) {
    dbPromise = (async () => {
      const db = await SQLite.openDatabaseAsync('app.db');
      await db.execAsync(
        'PRAGMA journal_mode = WAL;' +
          'CREATE TABLE IF NOT EXISTS notes (' +
          '  id TEXT PRIMARY KEY NOT NULL,' +
          '  body TEXT NOT NULL,' +
          '  updated_at INTEGER NOT NULL,' +
          '  deleted_at INTEGER' +
          ');' +
          'CREATE TABLE IF NOT EXISTS outbox (' +
          '  id INTEGER PRIMARY KEY AUTOINCREMENT,' +
          '  note_id TEXT NOT NULL,' +
          '  op TEXT NOT NULL,' +
          '  payload TEXT NOT NULL,' +
          "  status TEXT NOT NULL DEFAULT 'queued'," +
          '  created_at INTEGER NOT NULL' +
          ');'
      );
      return db;
    })();
  }
  return dbPromise;
}
export async function saveNote(id: string, body: string) {
  const db = await getDb();
  const now = Date.now();
  // One transaction: the row and its outbox entry are saved together or not at all.
  await db.withTransactionAsync(async () => {
    await db.runAsync(
      'INSERT OR REPLACE INTO notes (id, body, updated_at, deleted_at) VALUES (?, ?, ?, ?)',
      id, body, now, null
    );
    await db.runAsync(
      'INSERT INTO outbox (note_id, op, payload, created_at) VALUES (?, ?, ?, ?)',
      id, 'upsert', JSON.stringify({ id, body, updatedAt: now }), now
    );
  });
}

The Expo docs note that withTransactionAsync is not exclusive, so other async queries can run while it is open. If that matters for your data, read about withExclusiveTransactionAsync in the same docs.

Replay the outbox

Replaying has four rules. Send oldest first, so edits arrive in the order they were made. Delete a row only after the server accepts it, so a crash cannot lose a change. Stop at the first retryable failure, so order holds. Move a rejected change to failed instead of retrying it forever.

type SendResult = 'ok' | 'retry' | 'reject';

// You write this: one request to your server. Return 'retry' for network
// errors and server errors, 'reject' when the server says the change is invalid.
declare function sendToServer(op: string, payload: unknown): Promise<SendResult>;

let draining = false;

export async function drainOutbox() {
  if (draining) return; // the listener can fire many times
  draining = true;
  try {
    const db = await getDb();
    const rows = await db.getAllAsync<{ id: number; op: string; payload: string }>(
      'SELECT id, op, payload FROM outbox WHERE status = ? ORDER BY id',
      'queued'
    );
    for (const row of rows) {
      const result = await sendToServer(row.op, JSON.parse(row.payload));
      if (result === 'ok') {
        await db.runAsync('DELETE FROM outbox WHERE id = ?', row.id);
      } else if (result === 'reject') {
        await db.runAsync('UPDATE outbox SET status = ? WHERE id = ?', 'failed', row.id);
      } else {
        break; // keep order: stop here and try again on the next signal
      }
    }
  } finally {
    draining = false;
  }
}

Call drainOutbox from the connectivity listener, and also when the app starts and when it returns to the foreground. A change that was queued before the app was closed is still in the table, so it is sent on the next launch.

One more thing is yours to design: the server must tolerate the same change arriving twice, because a request can reach the server and its reply can still be lost. Give each change a stable id, as the sample does with id, and make the server write an upsert on that id.

Settle conflicts

A conflict happens when two devices change the same record before either syncs. You need a rule. For an app where one person edits their own data, last write wins is enough: keep the version with the newer updatedAt.

type Row = { id: string; body: string; updatedAt: number; deletedAt: number | null };

// Last write wins, per row. A delete is a row with deletedAt set.
export function mergeRow(local: Row | undefined, remote: Row): Row {
  if (!local) return remote;
  if (remote.updatedAt > local.updatedAt) return remote;
  return local; // on a tie, keep what is already here
}
  • Clocks. Phone clocks can be wrong. If the order of edits matters, let the server stamp updatedAt when it accepts a change, and send that value back.
  • Deletes. Do not remove the row. Set deletedAt and sync it like any other edit, so the other device learns the record is gone.
  • Lost edits. Last write wins throws the older edit away. If that is not acceptable for a field, such as a long note, keep both versions and ask the user.
  • Shared documents. When several people edit the same document at once, use a CRDT. Expo lists Yjs as a CRDT implementation.

Test it

  • Unit-test mergeRow with equal, newer and older timestamps and with a deleted row. It is a pure function, so these tests are short.
  • Unit-test the drain with a fake sendToServer that returns each of the three results.
  • On a real device, turn on airplane mode, create, edit and delete records, and check the screen updates without waiting.
  • Force-close the app while changes are queued, reopen it with the network on, and check the queue empties.
  • Edit the same record on two devices while both are offline, reconnect both, and check both end up with the same winner.
  • Make the server return an error once, and check the change is sent again and arrives once.

Where ShipNative fits

ShipNative turns a plain-English description into a React Native and Expo app that you can preview in the browser and in Expo Go, change by chat and download as a standard Expo project. As its offline apps page explains, an app built without a backend keeps its data on the phone with AsyncStorage, and an app connected to Supabase does not keep an offline copy of its synced data. So an AI builder can give you on-device storage, but it does not set up the outbox, the replay or the conflict rule from this guide. For those, take the downloaded project and add them yourself. Building an app needs a paid plan: Pro is $29/mo and Max is $49/mo.

Saurabh Singh

Written by

Saurabh Singh

Founder of ShipNative. Saurabh builds the product, answers support, and writes every guide on this site.

About

Frequently Asked Questions

What does offline-first mean?

The app reads and writes a database on the device, and the network is only used to sync that database with a server. Expo describes local-first the same way: the app works against local data, so it keeps working offline and syncs when it is connected.

Which local store should I use in Expo?

Use expo-sqlite for data you list, filter or update in groups, and for the outbox of unsent changes. Use MMKV or AsyncStorage for small values such as settings or a last-sync marker. The comparison table above links to a guide for each.

Is isConnected enough to decide whether to sync?

No. Expo says isConnected does not mean the internet is reachable. NetInfo says isInternetReachable is null when it is unknown. Treat connectivity as a hint to try a sync, and let a failed request put the change back in the queue.

Do I need a CRDT library to handle conflicts?

Not for most apps where one person edits their own data on a few devices. A last-write-wins rule with a timestamp on each row is enough there. CRDTs such as Yjs are for several people editing the same document at once. Expo lists Yjs as a CRDT implementation.

Should I write the sync layer myself?

Expo says local-first tools are still early and you may need to build a custom sync layer. It lists several libraries to look at first, including Legend-State, TinyBase, RxDB, Turso, PowerSync and Yjs. Writing a small outbox yourself, as shown below, is reasonable when a user edits only their own data.

How do I test offline behavior?

Test the merge function and the queue as plain functions with unit tests, then run through the flow on a real device: turn on airplane mode, make changes, force-close the app, turn the network back on, and check that the queue empties and the server has every change once.

→

Supabase vs Firebase 2026

Choosing the server your local database syncs with.

Read guide →
→

Connect an App to a Real Backend

Move from on-device data to a server.

Read guide →

Ship a real React Native app today

Describe, preview, and export Expo code, free to start.

Build with ShipNative
ShipNative

Build mobile apps with AI. Describe it, try it on your phone, own the code.

Features

Text to App AIApp Generator from ScreenshotPRD to Mobile AppDesign References

Tools

All free toolsApp Cost CalculatorApp Name GeneratorApp Store Keyword ToolReact Native Components

Blog

All blog postsHow to Build an App Without CodingBest AI Tools for Real Mobile AppsExpo EAS App Store ChecklistLovable, Cursor & v0 for MobileBest AI App Builders in 2026React Native AI App Builder Guide
© 2026 ShipNative
PrivacyTermsRefundsAboutFAQPricingDiscordShipNative - Featured on Startup FameFeatured on Twelve ToolsFeatured on TinyShelfShipNative - Launched on Fazier