React guide
Build a local-first React app with Sp00ky: provider, live queries, auth, mutations, sync status, files, CRDT fields and channels.
@spooky-sync/client-react connects React 18 and 19 apps to Sp00ky. Hooks such as useQuery
return plain values that stay live: every write lands in the local database first, the engine
syncs it with the server and every other tab and device in the background, and a component
re-renders only when the rows it reads actually changed. Reloads paint from the local cache, and
the app keeps working offline.
This guide builds a complete app: setup, queries, sign-in, writes, sync status, files, collaborative fields and peer to peer channels.
The client runs SurrealDB and SQLite as WebAssembly with IndexedDB / OPFS storage and web workers, which React Native does not have. Use it with React in the browser (Vite, Next.js client components, Remix); for a native mobile app use the Flutter guide.
Setup
- Install
- Configure the bundler
The client loads its engines as WebAssembly and starts web workers, both found next to its own files. With Vite, keep the client’s packages out of dependency pre-bundling (pre-bundled, they look in the wrong folder), pre-bundle the core’s CommonJS dependencies instead, and build for
esnext:vite.config.tsSee Client config for why each package is excluded.
- Generate types
This writes
schema.gen.tsfrom your.surqlschema: the table types every query and write is checked against. See Generated types. - Configure the clientsrc/db.ts
Every key is documented in Client config.
- Mount the providersrc/App.tsx
<Sp00kyProvider>creates the client, opens the local database and connects to the server, showingfallbackuntil it is ready. Its props:Prop Meaning configThe client config. Read once when the provider mounts; to switch databases, remount the provider with a new key.fallbackRendered until the client is ready. preloadAwaited before the children render, to warm the local cache. A failure is logged and the UI is revealed anyway. onReadyCalled with the client once it is ready. onErrorCalled if the client fails to start. eagerRender the children at once, before the client is ready. See below. The client is created in an effect, so a server render only produces the fallback. A client that was handed to the tree is deliberately not closed on unmount.
Rendering before the client is ready
By default nothing below the provider renders until the client has opened its local database.
With eager the children render at once:
With localEngine: 'rows', useQuery then returns,
on its very first render, the rows the query showed the last time the app was open, with
isLoading: false. The query starts as soon as the client is ready and replaces them when its
answer differs. Until then isAuthoritative is false, as for any query still loading.
What changes for your tree is that it mounts on a client that is not open yet:
- Queries and writes made early wait for the client. Nothing has to be reordered.
- Hooks that report state (
useSyncStatus,useFeatureFlag, auth) report their not-known-yet value until the client is ready. Gate what a signed-out visitor must not see onawait db.whenReady(), or ondb.isReady. fallbackis never rendered, andpreloadno longer holds the UI back.- It is for client-rendered trees. A server render still produces the fallback.
Rows only come back for queries that rendered in the first seconds of an earlier visit, on the
same browser, and only while no write has touched their tables since. That includes writes made
in another tab when sharedTabs is on.
Queries
useQuery(query, options?) subscribes a component to a live query. Build the query inline: the hook
re-registers only when the query’s identity (its SurrealQL and vars) changes, not when a new query
object is created on every render.
Pass null (or { enabled: false }) to skip a query until its inputs exist:
useQuery(db, query, options?) takes the client explicitly, for code outside a provider. The query
builder itself (where, related, orderBy, limit, one) is covered in
Reactive queries.
Result
useQuery returns plain values, recomputed only when they change:
| Field | Meaning |
|---|---|
data | Rows, or the row / null for .one(). [] / null before the first result. Structurally shared between updates. |
error | Registration or sync error (e.g. SSP 503 during bootstrap). Never thrown; the sync scheduler retries underneath. |
isLoading | Cold first load only: nothing painted for this query, the server has not answered, and registration has not failed. A paint from the local cache ends it; the server answering with zero rows ends it too. |
isFetching | The sync engine is pulling records for this query (registration, a sync round). |
isAuthoritative | data holds the rendered rows of a known membership: the server’s answer, or the one a previous session left on this device. From here data is an answer, not a cache guess. |
hasData | data holds something: rows for a list, a row for .one(). |
isEmpty | Authoritative and no data: the server said “no rows”. Render empty states on this, never on a bare !hasData. |
isSettled | Authoritative and idle. The gate for trusting a short window as the end of a list, and for “create it if it is missing”. Not monotonic: a later sync round re-enters isFetching. |
When the query’s identity changes, the previous data stays on screen until the new query
answers, while the flags reset. Growing a .limit() therefore never flashes an empty list:
Options: { enabled?: boolean, deregisterOnCleanup?: boolean }. Use deregisterOnCleanup for
viewport windows that mount and unmount a query per page, see Pagination.
Memoized rows
Because unchanged rows keep their identity, a memoized row component skips the render when another row changes:
Preloading
usePreload(query) warms the local cache for a query the user is likely to open next, without
subscribing to it. When they navigate, the page paints from the cache immediately:
Authentication
Sign-in runs through the SurrealDB access methods in your schema, see
Authentication. db.auth.subscribe reports the signed-in user id now and on
every change, which makes a small hook for the rest of the app:
A sign-in form wraps the call in useSubmission for its pending and error state:
Every live query is scoped by your table permissions, so a user only ever syncs the rows they may
read. db.signOut() ends the session and clears the local data.
Mutations
Writes are plain calls on the client. Each one commits locally, re-renders every query it affects, and syncs in the background, offline included:
For button pending and error state, wrap the call in useSubmission. submit is stable across
renders, always calls the latest function, and never rejects:
An error there means the local commit failed. Sync failures surface through useSyncStatus and
usePendingMutations instead. To track a backend job, query its outbox row: db.run() writes one
with status: 'pending'. See Mutations.
Sync status
useSyncStatus reports the connection, usePendingMutations the number of writes not yet on the
server. Together they make the usual offline banner:
| Hook | Returns |
|---|---|
useSyncStatus() | status, isHealthy, isDegraded, isOffline, isReconnecting, everConnected, connection, health |
usePendingMutations() | The number of local writes waiting to sync |
useSyncActivity(options?) | isDownloading, isUploading, fetchingQueries, pendingMutations, debounced for a traffic indicator |
useStorageStatus() | status, isPersistent, isMemoryFallback, health for the local database |
What to show for each state is covered in Offline & sync health.
Feature flags and releases
useFeatureFlag(key, options?) reads a feature flag for the signed-in
user and updates live when the assignment changes, so spky flag enable reaches open tabs without
a reload. useAppRelease tells a running tab that a newer frontend was deployed:
Files and images
useFileUpload and useDownloadFile upload to and read from a bucket.
<BucketImage> renders a bucket file as an image, revealing it only once it is decoded, and
<Blurhash> / useBlurhash paint a placeholder while it loads. The components take className,
style and imgClassName; useBucketImage gives you the same behaviour for custom markup.
Collaborative fields
A string field marked @crdt in the schema can be edited by several people at once.
useCrdtField(table, id, field) opens its document while the component is mounted and returns the
CrdtField, or null until it has loaded; show the column’s plain text until then:
Binding a rich text editor and showing remote cursors are covered in CRDT fields.
Peer to peer channels
useChannel(query, peers) opens a channel while the component is mounted,
for fast-changing state such as drafts or cursors that should reach other peers directly. Query and
peers are compared by value, so building them inline is fine; null closes the channel.
Admin impersonation
When an admin impersonates a user, the client shows a warning banner.
To render your own, set impersonationBanner: { mode: 'custom' } in the client config and read
useImpersonation({ rendersBanner: true }), which tells the client your banner is on screen:
Next.js and server rendering
The bundle starts with 'use client', so a server component (an App Router layout) can render
<Sp00kyProvider> directly. The provider renders its fallback on the server; data loads in the
browser, from the local cache first. Keep components that call the hooks below the provider and
inside client components.