# Offline-first data in React Native

The concrete setup behind `SKILL.md` §4. Open this when designing persistence, a write queue or a conflict rule.

Sources: https://tanstack.com/query/latest/docs/framework/react/react-native · https://tanstack.com/query/latest/docs/framework/react/plugins/persistQueryClient · https://docs.expo.dev/versions/latest/sdk/sqlite/ · https://orm.drizzle.team/docs/connect-expo-sqlite

## 1. Pick the store by the question it answers

| Data | Store | Why |
|---|---|---|
| Anything with a URL (server data) | TanStack Query cache, persisted | Caching, dedup and revalidation are solved; it is a cache, not state |
| Tokens, refresh tokens, PINs | `expo-secure-store` | Keychain / Keystore backed; the only place secrets belong |
| Settings, flags, last-seen ids, theme | `react-native-mmkv` | Synchronous, fast enough to read during render |
| Lists the user filters, sorts or edits offline | `expo-sqlite` (+ Drizzle) | Real queries, real indexes, survives cache eviction |
| Large binaries (photos, PDFs) | `expo-file-system` (`new File(...)`), keep URIs in the DB | Base64 in state is a memory leak waiting to happen |
| Sync-heavy collaborative data | WatermelonDB or a CRDT library | Only when the sync story genuinely needs it |

## 2. Wire the network state into the query client

```ts
// shared/lib/query.ts
import NetInfo from '@react-native-community/netinfo';
import { AppState, Platform, type AppStateStatus } from 'react-native';
import { QueryClient, focusManager, onlineManager } from '@tanstack/react-query';

onlineManager.setEventListener((setOnline) =>
  NetInfo.addEventListener((state) => setOnline(!!state.isConnected)),
);

AppState.addEventListener('change', (status: AppStateStatus) => {
  if (Platform.OS !== 'web') focusManager.setFocused(status === 'active');
});

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: { staleTime: 60_000, gcTime: 24 * 60 * 60 * 1000, networkMode: 'offlineFirst', retry: 2 },
    mutations: { networkMode: 'offlineFirst' },
  },
});
```

`networkMode: 'offlineFirst'` makes queries serve cached data and pause instead of erroring while offline, and mutations resume when connectivity returns.

## 3. Persist the cache to MMKV

```tsx
import { MMKV } from 'react-native-mmkv';
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import { queryClient } from '@/shared/lib/query';

const mmkv = new MMKV({ id: 'query-cache' });
const persister = createSyncStoragePersister({
  storage: {
    getItem: (k) => mmkv.getString(k) ?? null,
    setItem: (k, v) => mmkv.set(k, v),
    removeItem: (k) => mmkv.delete(k),
  },
});

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <PersistQueryClientProvider
      client={queryClient}
      persistOptions={{ persister, maxAge: 24 * 60 * 60 * 1000, buster: APP_BUILD_ID }}
    >
      {children}
    </PersistQueryClientProvider>
  );
}
```

Bump `buster` with every release that changes a payload shape, or an old cache will hydrate into new components. Never persist queries holding personal data you would not want on a stolen unlocked device — mark those with `gcTime: 0` and exclude them via `dehydrateOptions.shouldDehydrateQuery`.

## 4. Writes while offline: queue vs outbox

**Mutation queue** — good enough when a lost write is an inconvenience:

```ts
queryClient.setMutationDefaults(['orders', 'create'], {
  mutationFn: createOrder,
  retry: 3,
});
// resume paused mutations after rehydration
void queryClient.resumePausedMutations();
```

The queue lives in the persisted cache, so it survives a restart — but it is opaque to the user and cannot be inspected or edited.

**Outbox** — use it when the write must not be lost (orders, inspections, signatures):

```ts
// SQLite table: outbox(id, kind, payload, created_at, attempts, last_error)
export async function enqueue(kind: string, payload: unknown) { /* insert */ }
export async function drain() {
  for (const job of await pending()) {
    try { await send(job); await remove(job.id); }
    catch (e) { await bumpAttempts(job.id, String(e)); }        // exponential backoff, cap attempts
  }
}
```

Run `drain()` on connectivity regained (`onlineManager.subscribe`) and on app foreground. Show the user a pending count and a failure state — a silent queue is indistinguishable from data loss.

Every job needs an idempotency key generated on the device, so a retry after a timeout cannot create a duplicate server-side.

## 5. Local relational data with Drizzle

```ts
import { drizzle } from 'drizzle-orm/expo-sqlite';
import { openDatabaseSync } from 'expo-sqlite';
import { useMigrations } from 'drizzle-orm/expo-sqlite/migrator';
import migrations from '@/drizzle/migrations';

const sqlite = openDatabaseSync('app.db', { enableChangeListener: true });
export const db = drizzle(sqlite);

export function useReadyDatabase() {
  const { success, error } = useMigrations(db, migrations);
  return { ready: success, error };
}
```

`babel.config.js` needs `[["inline-import", { extensions: [".sql"] }]]`, `metro.config.js` needs `config.resolver.sourceExts.push('sql')`, and `drizzle.config.ts` needs `driver: 'expo'`. Hold the splash screen until `ready` — a migration that runs under a rendered screen produces "no such table" crashes.

## 6. Write the conflict rule down

| Strategy | Use when | Cost |
|---|---|---|
| Server authoritative (client discards local on conflict) | Read-mostly data, one editor | Simple; the user can lose an edit |
| Last write wins with a version column | Independent records, rare conflicts | Needs `updated_at`/`version` on both sides; silent overwrites |
| Field-level merge | Records edited by several people (status, notes) | Server must merge per field; more schema work |
| Explicit conflict UI | High-value records | Best data quality, most product work |

Decide per entity, not per app, and state it in the ADR. Then show the user what the conflict looks like on screen — the strategy is a product decision, not a technical one.

## 7. What each screen must declare

For every screen: what renders from cache with no network, what is disabled, what the user sees when a queued write is pending, and what happens when it finally fails. A screen that has not answered those four questions is not offline-ready, whatever the cache settings say.
