Expo and React Native apps need stable, offline-safe identifiers for local records before any server interaction. UUID v7 generated on the device carries a millisecond timestamp — records from multiple devices merge in chronological order during server sync. See UUID v7 in Expo and React Native for additional patterns.
Installation
npx expo install react-native-get-random-values uuid
Polyfill setup — critical import order
// index.ts or App.tsx — must be the FIRST import
import 'react-native-get-random-values';
// Only import uuid AFTER the polyfill
import { v7 as uuidv7 } from 'uuid';
export default function App() {
const id = uuidv7(); // safe to use anywhere after polyfill
// ...
}
Expo SQLite with UUID v7 primary keys
import * as SQLite from 'expo-sqlite';
import { v7 as uuidv7 } from 'uuid';
const db = SQLite.openDatabaseSync('myapp.db');
// Initialize schema
db.execSync(`
CREATE TABLE IF NOT EXISTS tasks (
id TEXT NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
completed INTEGER NOT NULL DEFAULT 0,
synced INTEGER NOT NULL DEFAULT 0
)
`);
// Create — UUID v7 encodes creation time on-device
export function createTask(title: string): string {
const id = uuidv7();
db.runSync('INSERT INTO tasks (id, title) VALUES (?, ?)', id, title);
return id;
}
// Read — cursor pagination, UUID v7 sort = chronological
export function listTasks(cursor?: string, limit = 20) {
const query = cursor
? 'SELECT * FROM tasks WHERE id > ? ORDER BY id LIMIT ?'
: 'SELECT * FROM tasks ORDER BY id LIMIT ?';
const args = cursor ? [cursor, limit] : [limit];
const rows = db.getAllSync<{ id: string; title: string; completed: number }>(query, ...args);
return {
tasks: rows,
nextCursor: rows.length === limit ? rows.at(-1)!.id : null,
};
}
Offline sync queue
interface SyncRecord {
id: string; // UUID v7 — when the action occurred
type: 'create' | 'update' | 'delete';
table: string;
payload: string; // JSON
}
// Queue an operation while offline
export function queueSync(type: SyncRecord['type'], table: string, payload: object) {
const id = uuidv7(); // UUID v7 timestamp = when the user performed the action
db.runSync(
'INSERT INTO sync_queue (id, type, table_name, payload) VALUES (?, ?, ?, ?)',
id, type, table, JSON.stringify(payload)
);
return id;
}
// Flush — UUID v7 ORDER BY = replay actions in user's original order
export async function flushSync() {
const pending = db.getAllSync<SyncRecord>(
'SELECT * FROM sync_queue WHERE synced = 0 ORDER BY id'
);
for (const record of pending) {
await fetch('/api/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: record.payload,
});
db.runSync('UPDATE sync_queue SET synced = 1 WHERE id = ?', record.id);
}
}
AsyncStorage session ID
import AsyncStorage from '@react-native-async-storage/async-storage';
import { v7 as uuidv7 } from 'uuid';
const KEY = '@session_uuid_v7';
export async function getOrCreateSessionId(): Promise<string> {
const stored = await AsyncStorage.getItem(KEY);
if (stored) return stored;
const id = uuidv7(); // new session — UUID v7 encodes session start time
await AsyncStorage.setItem(KEY, id);
return id;
}
// Extract session start time from UUID v7 — no extra metadata needed
export function getSessionStartMs(sessionId: string): number {
return parseInt(sessionId.replace(/-/g, '').slice(0, 12), 16);
}
TypeScript utility hook
import { useCallback } from 'react';
import { v7 as uuidv7 } from 'uuid';
export function useUuidV7() {
const generate = useCallback(() => uuidv7(), []);
const extractTimestamp = useCallback((id: string): Date => {
const hex = id.replace(/-/g, '').slice(0, 12);
return new Date(parseInt(hex, 16));
}, []);
return { generate, extractTimestamp };
}
Further reading
- UUID v7 in Expo and React Native — news
- UUID in SQLite
- UUID v7 in Distributed Systems
- UUID in JavaScript
- UUID in Mobile Apps
External references
Frequently asked questions
Why does UUID generation fail in React Native without a polyfill?
React Native's JavaScript engine (Hermes or JSC) does not expose crypto.getRandomValues() by default. The uuid npm package calls this API internally. Without it, UUID generation throws TypeError: crypto.getRandomValues is not a function. The fix is to import react-native-get-random-values before any uuid import — this patches the global crypto object with a native implementation. See UUID v7 in Expo and React Native.
Does Expo SDK provide a built-in UUID v7 generator?
expo-crypto provides randomUUID() which generates UUID v4 only. For UUID v7, install the uuid npm package with the react-native-get-random-values polyfill. UUID v7's timestamp prefix enables offline-first sync ordering — UUID v4 does not provide this. See UUID in JavaScript.
How do I use UUID v7 as a primary key in Expo SQLite?
In Expo SQLite (expo-sqlite v13+), define the primary key as id TEXT NOT NULL PRIMARY KEY. Insert UUID v7 strings generated with the uuid npm package. SQLite sorts TEXT columns lexicographically — UUID v7 lexicographic order equals chronological, so ORDER BY id is a time-ordered sort with no secondary column. See UUID in SQLite.