Use SignalDB with React Native
SignalDB runs in React Native the same way it runs in the browser. @signaldb/core supports Hermes, and the React bindings work unchanged. Three things are different on a phone, and this guide is about them:
- There is no IndexedDB, OPFS or
localStorage. The browser storage adapters don't work on a phone. On the device you persist in SQLite, with@signaldb/sqlite. - There are no web workers. The JS thread is the thread that renders your UI, so a query that is expensive in JavaScript costs frames. If you want the data layer somewhere else, you run it on a second JS runtime.
- The app lifecycle is different. A JS runtime can outlive the root component, Fast Refresh re-evaluates modules, and Expo Go cannot load custom native code.
This guide builds on the React guide. Read that one first if you haven't used SignalDB with React before.
Prerequisites
You need a React Native project, either bare or with Expo. The examples use Expo modules where a native module is needed. A basic understanding of signal-based reactivity and of data adapters helps.
Installation
Install SignalDB, a signals library with its reactivity adapter, and the React bindings, exactly as on the web:
npm install @signaldb/core @maverick-js/signals @signaldb/maverickjs @signaldb/reactFor persistence on the device, install the SQLite storage adapter and a SQLite library. This guide uses expo-sqlite:
npm install @signaldb/sqlite
npx expo install expo-sqliteReactivity
Create the reactivity hook once and import it wherever you read data:
// useReactivity.ts
import { effect, peek } from '@maverick-js/signals'
import { createUseReactivityHook } from '@signaldb/react'
const useReactivity = createUseReactivityHook((reactiveFunction: () => void) =>
peek(() => effect(() => {
try {
reactiveFunction()
} catch (error) {
if (__DEV__) console.error('A reactive query threw', error)
}
})))
export default useReactivityThe two differences from the React guide matter more in an app than on a web page:
try/catchinside the effect. With Maverick Signals, an error that escapes an effect leaves the effect scheduler in a state where no effect is scheduled again. One query throwing (for example while a write races it) would freeze every reactive read in the app until it restarts. A web page gets reloaded; an app may stay in memory for days. If you need the error, store it and rethrow it during render, so an error boundary can handle it.peek. Creating the effect insidepeekkeeps it from being tracked by an outer reactive scope that the hook happens to run in.
Choosing a data adapter
Pick the data adapter by how much data a collection holds:
| Where queries run | First read | Use when | |
|---|---|---|---|
DefaultDataAdapter | In memory, on the JS thread | Synchronous, after loading everything at startup | The data is small: settings, a few hundred items |
AsyncDataAdapter | In SQLite, called from the JS thread | Asynchronous | The data does not fit comfortably in memory, or loading all of it at startup takes too long |
WorkerDataAdapter on a worklet runtime | On a second JS runtime | Asynchronous | Queries and writes are large enough to cost frames on the JS thread |
All three take the same storage adapter, so you can start with the first and move to another one later without changing your collections or components.
Persisting collections with SQLite
@signaldb/sqlite persists collections in SQLite. It doesn't depend on a specific SQLite library. You connect it to yours through a driver with two methods, which for expo-sqlite looks like this:
// db.ts
import { AsyncDataAdapter } from '@signaldb/core'
import createSQLiteAdapter from '@signaldb/sqlite'
import type { SQLiteDriver, SQLiteValue } from '@signaldb/sqlite'
import { openDatabaseSync } from 'expo-sqlite'
const database = openDatabaseSync('app.db')
database.execSync('PRAGMA journal_mode = WAL')
const driver: SQLiteDriver = {
execute: (sql, parameters) => database.runAsync(sql, parameters),
select: <R>(sql: string, parameters: SQLiteValue[]) => database.getAllAsync<R>(sql, parameters),
}
export const dataAdapter = new AsyncDataAdapter({
storage: name => createSQLiteAdapter(driver, name),
onError: error => console.error('[SignalDB]', error),
})// collections/Todos.ts
import { Collection } from '@signaldb/core'
import maverickReactivityAdapter from '@signaldb/maverickjs'
import { dataAdapter } from '../db'
export type Todo = { id: string, text: string, listId: string, done: boolean }
const Todos = new Collection<Todo>('todos', dataAdapter, {
reactivity: maverickReactivityAdapter,
indices: ['listId'],
})
export default TodosCreate the driver once and share it between all collections. The adapter queues all writes per driver, because SQLite runs one transaction per connection at a time. Two collections with their own drivers on the same connection would open a transaction inside another one.
With AsyncDataAdapter and WorkerDataAdapter, every query goes to SQLite. An equality on id or on an indexed field reads only the matching rows. Any other query reads the whole table and is filtered in JavaScript, so declare an index for every field your selectors filter on. See the reference for how collections are stored and for drivers for op-sqlite and node:sqlite.
When to write your own storage adapter
@signaldb/sqlite stores every document as JSON. If you need your own schema (real columns per field, your own migrations, or SQL that sorts and limits for you), write a storage adapter with createStorageAdapter. Two things are easy to get wrong:
- Index keys are
serializeValue(value), not the raw field value. An index keyed by raw values answers nothing for every non-string field, and nothing points you to the cause. See Index keys. - Only report a query as sorted when the order is the same as SignalDB's. SQLite compares text by its UTF-8 bytes, JavaScript by UTF-16 code units. For timestamps or ASCII codes that's the same; for free text it isn't.
Reading data in components
AsyncDataAdapter and WorkerDataAdapter cannot answer a query on the spot. A reactive query first returns its neutral result (an empty list, a count of zero) and updates once the answer arrives. An empty list is also a legitimate answer, so use Cursor#isLoading() to tell the two apart:
import { ActivityIndicator, FlatList, Text } from 'react-native'
import useReactivity from './useReactivity'
import Todos from './collections/Todos'
const TodoList = ({ listId }: { listId: string }) => {
const { loading, todos } = useReactivity(() => {
const cursor = Todos.find({ listId }, { sort: { text: 1 } })
return { loading: cursor.isLoading(), todos: cursor.fetch() }
}, [listId])
if (loading) return <ActivityIndicator />
return (
<FlatList
data={todos}
keyExtractor={todo => todo.id}
renderItem={({ item }) => <Text>{item.text}</Text>}
/>
)
}Outside a component (in an event handler, a background task or your business logic), await the query instead:
const openTodos = await Todos.find({ listId, done: false }, { async: true }).fetch()A query read synchronously outside a reactive scope logs the Cursor.depend() warning. Treat that warning as a bug: the read is answered with the neutral result and never updates. See Queries that are not answered immediately.
Keeping queries off the JS thread
If your collections are large enough that querying them costs frames, run the data layer on a second JS runtime. React Native has no web workers, but react-native-worklets can create one with createWorkletRuntime. SignalDB's WorkerDataAdapter does not need a real Worker: it takes anything that implements WorkerDataAdapterEndpoint, and the host takes anything that implements WorkerDataAdapterHostEndpoint. So the setup is two small endpoints that pass messages between the runtimes:
import { WorkerDataAdapter, WorkerDataAdapterHost } from '@signaldb/core'
import type { WorkerDataAdapterEndpoint } from '@signaldb/core'
import { createWorkletRuntime, scheduleOnRN, scheduleOnRuntime } from 'react-native-worklets'
import createSQLiteAdapter from '@signaldb/sqlite'
import workletDriver from './workletDriver' // see below
type HostScope = typeof globalThis & {
signalDbHostListeners: Set<(event: MessageEvent) => unknown>
}
const runtime = createWorkletRuntime({ name: 'signaldb' })
const listeners = new Set<(event: MessageEvent) => void>()
let readyMessage: string | null = null
// JS thread: receives messages from the host
const receiveFromHost = (serialized: string) => {
const data: unknown = JSON.parse(serialized)
if ((data as { type?: string }).type === 'ready') readyMessage = serialized
listeners.forEach(listener => listener({ data } as MessageEvent))
}
// worklet runtime: starts the host once
const startHost = () => {
'worklet'
const hostListeners = new Set<(event: MessageEvent) => unknown>()
;(globalThis as HostScope).signalDbHostListeners = hostListeners
new WorkerDataAdapterHost({
addEventListener: (_type, listener) => { hostListeners.add(listener) },
postMessage: message => scheduleOnRN(receiveFromHost, JSON.stringify(message)),
}, {
id: 'app-data',
storage: name => createSQLiteAdapter(workletDriver, name),
})
}
// worklet runtime: receives messages from the JS thread
const receiveFromAdapter = (serialized: string) => {
'worklet'
const data: unknown = JSON.parse(serialized)
;(globalThis as HostScope).signalDbHostListeners.forEach(listener => listener({ data } as MessageEvent))
}
scheduleOnRuntime(runtime, startHost)
const endpoint: WorkerDataAdapterEndpoint = {
addEventListener: (_type, listener) => {
listeners.add(listener)
if (readyMessage) listener({ data: JSON.parse(readyMessage) } as MessageEvent)
},
removeEventListener: (_type, listener) => { listeners.delete(listener) },
postMessage: message => scheduleOnRuntime(runtime, receiveFromAdapter, JSON.stringify(message)),
}
export const dataAdapter = new WorkerDataAdapter(endpoint, { id: 'app-data' })The sketch shows the shape. Before you use it, know about these constraints:
Storage has to be reachable from the worklet runtime. The host and its storage adapter run there, so the SQLite connection must be callable from that runtime. JS modules like
expo-sqliteare installed on the main JS runtime, not on a runtime you create. In practice this means a small native module that installs a JSI-based SQLite binding into the worklet runtime. Map that binding onto aSQLiteDriver, and@signaldb/sqliteworks there unchanged.Make
@signaldb/coreand@signaldb/sqliteimportable in the worklet runtime. With the worklets Babel plugin in bundle mode, list them underimportForwarding. OtherwiseWorkerDataAdapterHostis copied into the worklet's closure as a remote function, and constructing it fails withTried to synchronously call a Remote Function:js// babel.config.js plugins: [['react-native-worklets/plugin', { bundleMode: true, importForwarding: { moduleNames: ['@signaldb/core', '@signaldb/sqlite'] }, }]]Every message is serialized, and decoded on the JS thread. The work happens on the worklet runtime, but parsing the answer does not. Keep messages small: project queries with
fieldsto the fields you render, and remember that the host sends deltas after the first answer. Don't pass a reviver toJSON.parseon the hot path. On Hermes a reviver makes the cost grow with the number of keys in the payload, not with its size.The host must announce itself within five seconds. If the adapter does not hear the host's
readymessage in time, every operation fails withWorkerDataAdapter initialization timed out. Replay thereadymessage to listeners that register late (as above), and if you have to run migrations before the first query, buffer the adapter's outgoing messages until then rather than delaying the host.
App lifecycle and Hermes
Open the database once per JS runtime, not per mount. On Android, the root component can be unmounted and mounted again in the same JS runtime: when the activity is recreated after a configuration change, or when the user presses Back on the root screen. Keep the database and the collections at module scope, and memoize the startup promise, so a second mount joins the first startup instead of opening a second connection.
Survive Fast Refresh. When a module is evaluated again, a
new Collection(...)at its top level creates a second collection over the same table. During development, keep collections onglobalThisunder aSymbol.for(...)key and reuse them when they exist.Load exactly one copy of
@signaldb/core.Collectionhas static state, for example the threshold set byCollection.reportLargeQueries(). If Metro resolves two copies (a linked package, a monorepo with nestednode_modules), statics set on one copy don't affect collections built from the other. If you link SignalDB locally, add the linked package and thenode_modulesdirectories above it to Metro'swatchFolders.Expo Go cannot load custom native modules. If your app uses a native SQLite binding for the worklet runtime, fall back to
AsyncDataAdapterwithexpo-sqlitewhen running in Expo Go. Both adapters answer queries asynchronously, so components behave the same either way.Your own code runs on Hermes too. SignalDB core supports Hermes, but your SQLite driver and any worklet code are your own. Before you use a recent language or standard-library feature in them, check that Hermes supports it.
Report large live queries in development. A reactive query is evaluated again on every write to its collection. One that holds thousands of rows works correctly but makes every write slow, and nothing visible warns you. Turn on
Collection.reportLargeQueries()in development builds, before the first collection is created:tsif (__DEV__) Collection.reportLargeQueries(200)
Synchronizing with a backend
Syncing works the same in React Native as everywhere else. See the Synchronization Overview to get started.
Next Steps
- Data Adapters: what each adapter does and when to switch.
@signaldb/sqlite: how collections are stored, transactions, and drivers for other SQLite libraries.- Storage Adapters: the storage contract in detail.
createStorageAdapter: the reference, including the optionalquerymethod.WorkerDataAdapter: the worker boundary and its costs.