Github|...

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.

React DOM, not React Native

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

  1. Install
    pnpm add @spooky-sync/core @spooky-sync/client-react
    pnpm add -D vite-plugin-wasm
  2. 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.ts
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import wasm from 'vite-plugin-wasm';
    
    export default defineConfig({
      plugins: [react(), wasm()],
      optimizeDeps: {
        // Served as is: pre-bundled, these look for their .wasm files and
        // workers in the wrong folder.
        exclude: [
          '@spooky-sync/client-react',
          '@spooky-sync/core',
          '@spooky-sync/ssp-wasm',
          '@surrealdb/wasm',
          '@surrealdb/wasm-native',
          '@sqlite.org/sqlite-wasm',
        ],
        // The excluded core's CommonJS dependencies, pre-bundled for it.
        include: ['@spooky-sync/core > pino', '@spooky-sync/core > fast-json-patch'],
      },
      // The client uses top-level await.
      build: { target: 'esnext' },
    });

    See Client config for why each package is excluded.

  3. Generate types
    # Driven by the clientTypes entries in sp00ky.yml
    spky generate

    This writes schema.gen.ts from your .surql schema: the table types every query and write is checked against. See Generated types.

  4. Configure the client
    src/db.ts
    import type { SyncedDbConfig } from '@spooky-sync/client-react';
    import { schema, SURQL_SCHEMA } from './schema.gen';
    
    export const dbConfig: SyncedDbConfig<typeof schema> = {
      logLevel: 'info',
      schema,
      schemaSurql: SURQL_SCHEMA,
      database: {
        namespace: 'main',
        database: 'main',
        // spky dev exposes SurrealDB on 8666 by default.
        endpoint: 'ws://localhost:8666/rpc',
        store: 'indexeddb',
      },
    };

    Every key is documented in Client config.

  5. Mount the provider
    src/App.tsx
    import { Sp00kyProvider } from '@spooky-sync/client-react';
    import { dbConfig } from './db';
    import { MainContent } from './MainContent';
    
    export default function App() {
      return (
        <Sp00kyProvider
          config={dbConfig}
          fallback={<div>Initializing database…</div>}
          preload={async (db) => {
            // Optional: warm the local cache before the UI is revealed.
            await db.preload(db.query('config').build());
          }}
          onError={(err) => console.error('Failed to initialize database:', err)}
        >
          <MainContent />
        </Sp00kyProvider>
      );
    }

    <Sp00kyProvider> creates the client, opens the local database and connects to the server, showing fallback until it is ready. Its props:

    PropMeaning
    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:

src/App.tsx
<Sp00kyProvider config={dbConfig} eager>
  <App />
</Sp00kyProvider>

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 on await db.whenReady(), or on db.isReady.
  • fallback is never rendered, and preload no 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.

src/components/PostList.tsx
import { useDb, useQuery } from '@spooky-sync/client-react';
import type { schema } from '../schema.gen';

export function PostList() {
  const db = useDb<typeof schema>();
  const posts = useQuery(
    db.query('post').related('author').orderBy('created_at', 'desc').limit(20).build()
  );

  if (posts.isLoading) return <div>Loading…</div>;
  if (posts.isEmpty) return <div>No posts yet.</div>;
  return (
    <ul>
      {posts.data.map((post) => (
        <li key={String(post.id)}>
          {post.title} by {post.author?.username}
        </li>
      ))}
    </ul>
  );
}

Pass null (or { enabled: false }) to skip a query until its inputs exist:

const post = useQuery(
  postId ? db.query('post').where({ id: postId }).one().build() : null
);

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:

FieldMeaning
dataRows, or the row / null for .one(). [] / null before the first result. Structurally shared between updates.
errorRegistration or sync error (e.g. SSP 503 during bootstrap). Never thrown; the sync scheduler retries underneath.
isLoadingCold 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.
isFetchingThe sync engine is pulling records for this query (registration, a sync round).
isAuthoritativedata 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.
hasDatadata holds something: rows for a list, a row for .one().
isEmptyAuthoritative and no data: the server said “no rows”. Render empty states on this, never on a bare !hasData.
isSettledAuthoritative 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:

const [limit, setLimit] = useState(20);
const posts = useQuery(db.query('post').orderBy('created_at', 'desc').limit(limit).build());

<button disabled={!posts.isSettled} onClick={() => setLimit((n) => n + 20)}>
  Load more
</button>

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:

const PostRow = memo(function PostRow({ post }: { post: Post }) {
  return <li>{post.title}</li>;
});

{posts.data.map((post) => <PostRow key={String(post.id)} post={post} />)}

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:

import { useDb, usePreload } from '@spooky-sync/client-react';

function ThreadLink({ id }: { id: string }) {
  const db = useDb<typeof schema>();
  usePreload(db.query('thread').where({ id }).related('comments').one().build());
  return <Link to={'/thread/' + id}>Open</Link>;
}

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:

src/lib/auth.ts
import { useEffect, useState } from 'react';
import { useDb } from '@spooky-sync/client-react';
import type { schema } from '../schema.gen';

export function useAuth() {
  const db = useDb<typeof schema>();
  // undefined until the client reports, then a user id or null.
  const [userId, setUserId] = useState<string | null | undefined>(undefined);

  // subscribe() answers right away with the current user, then on every
  // sign-in and sign-out. It returns the unsubscribe the effect cleans up with.
  useEffect(() => db.auth.subscribe(setUserId), [db]);

  return {
    userId,
    isChecking: userId === undefined,
    signIn: (username: string, password: string) =>
      db.auth.signIn('account', { username, password }),
    signUp: (username: string, password: string) =>
      db.auth.signUp('account', { username, password }),
    signOut: () => db.signOut(),
  };
}

A sign-in form wraps the call in useSubmission for its pending and error state:

src/components/SignIn.tsx
import { useState } from 'react';
import { useSubmission } from '@spooky-sync/client-react';
import { useAuth } from '../lib/auth';

export function SignIn() {
  const auth = useAuth();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const signIn = useSubmission(auth.signIn);

  if (auth.isChecking) return null;
  if (auth.userId) return <button onClick={auth.signOut}>Sign out</button>;

  return (
    <form onSubmit={(e) => { e.preventDefault(); void signIn.submit(username, password); }}>
      <input value={username} onChange={(e) => setUsername(e.target.value)} />
      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button disabled={signIn.pending}>Sign in</button>
      {signIn.error && <p>{signIn.error.message}</p>}
    </form>
  );
}

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:

import { RecordId } from '@spooky-sync/client-react';

// Create takes a full record id and the row.
await db.create('post:' + crypto.randomUUID(), {
  title: 'Hi',
  author: new RecordId('user', userId),
});

// Update merges only the listed fields.
await db.update('post', 'post:xyz', { title: 'Edited' });

// Delete takes an id string or the RecordId a live row carries.
await db.delete('post', row.id);

// Run a backend job through the outbox.
await db.run('backend', 'sendMail', { to });

For button pending and error state, wrap the call in useSubmission. submit is stable across renders, always calls the latest function, and never rejects:

import { useState } from 'react';
import { useDb, useSubmission } from '@spooky-sync/client-react';

function NewPost() {
  const db = useDb<typeof schema>();
  const [title, setTitle] = useState('');
  const save = useSubmission((t: string) => db.create('post:' + crypto.randomUUID(), { title: t }));

  return (
    <form onSubmit={(e) => { e.preventDefault(); void save.submit(title); }}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} />
      <button disabled={save.pending}>Save</button>
      {save.error && <p>{save.error.message}</p>}
    </form>
  );
}

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:

import { useSyncStatus, usePendingMutations } from '@spooky-sync/client-react';

function ConnectionBanner() {
  const sync = useSyncStatus();
  const pending = usePendingMutations();
  if (!sync.isDegraded) return null;
  return <Banner>Can't reach the server, {pending} change(s) queued.</Banner>;
}
HookReturns
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:

import { useAppRelease, useFeatureFlag } from '@spooky-sync/client-react';

function Toolbar() {
  const newEditor = useFeatureFlag('new-editor', { fallback: 'off' });
  return newEditor.enabled ? <NewEditorButton /> : <EditorButton />;
}

function UpdatePrompt() {
  const release = useAppRelease({ app: 'web', currentVersion: __APP_VERSION__ });
  if (!release.updateAvailable) return null;
  return <button onClick={() => release.reload()}>Update to {release.latestVersion}</button>;
}

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.

import { BucketImage, useFileUpload } from '@spooky-sync/client-react';

function Avatar({ path }: { path: string | null }) {
  return <BucketImage bucket="avatars" path={path} className="h-12 w-12 rounded-full" alt="" />;
}

function AvatarUpload() {
  const { upload, isUploading, error } = useFileUpload('avatars');
  return (
    <input
      type="file"
      disabled={isUploading}
      onChange={(e) => {
        const file = e.target.files?.[0];
        if (file) void upload(crypto.randomUUID() + '.png', file);
      }}
    />
  );
}

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:

import { useEffect, useState } from 'react';
import { useCrdtField } from '@spooky-sync/client-react';

// id is the full record id, e.g. 'note:abc'; summary is the column's plain text.
function Summary({ id, summary }: { id: string; summary: string }) {
  const field = useCrdtField('note', id, 'summary');
  const [value, setValue] = useState(summary);

  // Follow the document: local and remote edits alike re-render the input.
  useEffect(() => {
    const doc = field?.getDoc();
    if (!doc) return;
    const text = doc.getText('summary');
    setValue(text.toString());
    return doc.subscribe(() => setValue(text.toString()));
  }, [field]);

  return (
    <textarea
      value={value}
      readOnly={!field}
      onChange={(e) => {
        const doc = field?.getDoc();
        if (!doc) return;
        doc.getText('summary').update(e.target.value); // minimal diff
        doc.commit();
      }}
    />
  );
}

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.

import { useChannel } from '@spooky-sync/client-react';

const ch = useChannel(db.query('message').where({ conversation: convoId }), [me, other]);
// ch.status: 'idle' | 'connecting' | 'connected' | 'failed' | 'unsupported'
await ch.update('message', id, { draft: text });

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:

import { useImpersonation } from '@spooky-sync/client-react';

function ImpersonationBar() {
  const { impersonation, stop } = useImpersonation({ rendersBanner: true });
  if (!impersonation) return null;
  return (
    <div className="banner">
      Acting as {impersonation.target} <button onClick={() => void stop()}>Stop</button>
    </div>
  );
}

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.

Next