The short version
- Write locally. Save the change to the local database and add a row to the outbox in one transaction. The screen updates now.
- Notice the network. A connectivity listener tells you when a sync is worth trying.
- Replay the outbox. Send queued changes oldest first. Delete a row only after the server accepts it.
- 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.
| Store | What it is | Use it for | Guide |
|---|---|---|---|
expo-sqlite | A 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-mmkv | Key-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 |
AsyncStorage | Asynchronous, 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 state | Meaning |
|---|---|
queued | Saved on the device, not sent yet. |
sending | A request is in flight. |
accepted | The server confirmed it. Delete the outbox row. |
failed | The 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
updatedAtwhen it accepts a change, and send that value back. - Deletes. Do not remove the row. Set
deletedAtand 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
mergeRowwith 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
sendToServerthat 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.
