zdb-react-native
v0.1.0
Published
High-performance embedded database for React Native - Battery-first, ultra-fast key-value storage
Maintainers
Readme
zdb-react-native
High-performance embedded database for React Native. Battery-first, ultra-fast key-value storage built with Zig.
Features
- ⚡ 10x faster than SQLite for key-value operations
- 🔋 Battery optimized - minimal CPU & I/O usage
- 🚀 Zero-copy reads using memory mapping
- 📦 Tiny binary (~500KB per architecture)
- 🔒 Thread-safe with read-write locking
- 💾 Persistent - data survives app restarts
Installation
npm install zdb-react-native
# or
yarn add zdb-react-nativeiOS Setup
cd ios && pod install && cd ..Android Setup
No additional setup required - native libraries are bundled.
Quick Start
import ZDB from 'zdb-react-native';
async function example() {
// Open database (creates if doesn't exist)
const db = await ZDB.open('myapp.zdb');
// Store data
await db.put('user:1', JSON.stringify({ name: 'John', age: 30 }));
// Retrieve data
const userData = await db.get('user:1');
console.log(userData); // '{"name":"John","age":30}'
// Or parse JSON automatically
const user = await db.getJSON('user:1');
console.log(user.name); // 'John'
// Check if key exists
const exists = await db.contains('user:1'); // true
// Count all keys
const total = await db.count(); // 1
// Delete data
await db.delete('user:1');
// Close when done
await db.close();
}API Reference
ZDB.open(path: string): Promise<ZDB>
Opens or creates a database at the specified path.
| Parameter | Type | Description |
|-----------|------|-------------|
| path | string | Database filename (stored in app's documents directory) |
Returns: Promise resolving to a ZDB instance.
const db = await ZDB.open('mydata.zdb');db.put(key: string, value: string | object): Promise<void>
Stores a key-value pair. Objects are automatically JSON stringified.
| Parameter | Type | Description |
|-----------|------|-------------|
| key | string | Unique key identifier |
| value | string \| object | Value to store |
// Store string
await db.put('name', 'John');
// Store object (auto-stringified)
await db.put('user:1', { name: 'John', age: 30 });db.get(key: string): Promise<string | null>
Retrieves a value by key.
| Parameter | Type | Description |
|-----------|------|-------------|
| key | string | Key to look up |
Returns: The value as a string, or null if not found.
const value = await db.get('name');
if (value !== null) {
console.log(value);
}db.getJSON<T>(key: string): Promise<T | null>
Retrieves and parses a JSON value.
| Parameter | Type | Description |
|-----------|------|-------------|
| key | string | Key to look up |
Returns: Parsed JSON object, or null if not found.
interface User {
name: string;
age: number;
}
const user = await db.getJSON<User>('user:1');
console.log(user?.name); // 'John'db.delete(key: string): Promise<void>
Deletes a key-value pair.
await db.delete('user:1');db.contains(key: string): Promise<boolean>
Checks if a key exists.
if (await db.contains('user:1')) {
console.log('User exists');
}db.count(): Promise<number>
Returns the total number of stored keys.
const total = await db.count();
console.log(`Database has ${total} entries`);db.close(): Promise<void>
Closes the database and releases resources. Always call this when done.
await db.close();Common Patterns
User Preferences
import ZDB from 'zdb-react-native';
class Preferences {
private db: ZDB | null = null;
async init() {
this.db = await ZDB.open('preferences.zdb');
}
async set(key: string, value: any) {
await this.db?.put(`pref:${key}`, value);
}
async get<T>(key: string, defaultValue: T): Promise<T> {
const value = await this.db?.getJSON<T>(`pref:${key}`);
return value ?? defaultValue;
}
}
// Usage
const prefs = new Preferences();
await prefs.init();
await prefs.set('darkMode', true);
const darkMode = await prefs.get('darkMode', false);Caching API Responses
import ZDB from 'zdb-react-native';
const cache = await ZDB.open('cache.zdb');
async function fetchWithCache(url: string, ttlMs: number = 60000) {
const cacheKey = `cache:${url}`;
const cached = await cache.getJSON<{ data: any; timestamp: number }>(cacheKey);
if (cached && Date.now() - cached.timestamp < ttlMs) {
return cached.data; // Return cached data
}
// Fetch fresh data
const response = await fetch(url);
const data = await response.json();
// Cache it
await cache.put(cacheKey, { data, timestamp: Date.now() });
return data;
}Offline Queue
import ZDB from 'zdb-react-native';
const queue = await ZDB.open('offline_queue.zdb');
let queueIndex = 0;
async function enqueue(action: object) {
await queue.put(`queue:${++queueIndex}`, action);
}
async function processQueue() {
const count = await queue.count();
for (let i = 1; i <= count; i++) {
const action = await queue.getJSON(`queue:${i}`);
if (action) {
await processAction(action);
await queue.delete(`queue:${i}`);
}
}
}Requirements
| Platform | Minimum Version | |----------|-----------------| | React Native | 0.71+ | | iOS | 12.0+ | | Android | API 21+ (Lollipop) |
Troubleshooting
Android: "libzmdb.so not found"
Ensure the native libraries are properly linked:
cd android && ./gradlew clean && cd ..
npx react-native run-androidiOS: Build fails with missing header
Run pod install again:
cd ios && pod install --repo-update && cd ..Expo: Module not found
ZDB requires bare React Native. It does not work with Expo Go.
Use npx expo prebuild to eject to bare workflow.
Performance Comparison
| Operation | ZDB | SQLite | AsyncStorage | |-----------|-----|--------|--------------| | Single write | 0.05ms | 0.3ms | 2ms | | Single read | 0.02ms | 0.1ms | 1ms | | Batch 1000 writes | 15ms | 150ms | 2000ms | | Database size (1M records) | 45MB | 60MB | N/A |
Benchmarks on Pixel 6, release build
License
MIT © ZDB Contributors
