@syncular/react
v0.98.0
Published
React hooks for Syncular offline-first sync
Maintainers
Readme
@syncular/react
React 18+ bindings for Syncular's revisioned reactive store. The same hooks work with the direct TypeScript client, the browser worker handle, and the Tauri/React Native bridges.
The store is client-scoped, not hook-scoped. Equal queries share one local SQL
read per revision, rows and window completeness come from one SQLite snapshot,
and stale promises cannot overwrite a newer revision. Status, conflict, and
outcome refreshes discard older pending results after a newer read or event.
Presence reads follow the same ordering and clear peers when the client or
scope changes. React is only a
useSyncExternalStore adapter over that renderer-independent state.
Recommended query and mutation path
Author reads in queries/*.sql or queries/*.syql, run syncular generate,
and pass the generated descriptor to useQuery:
import { SyncProvider, useMutation, useQuery } from '@syncular/react';
import { tasksTable } from './syncular.generated';
import { listTasksQuery } from './syncular.queries';
function Tasks({ projectId }: { projectId: string }) {
const tasks = useQuery(listTasksQuery, { projectId });
const mutation = useMutation(tasksTable);
if (tasks.phase === 'loading') return <p>Loading…</p>;
if (tasks.phase === 'blocked' && tasks.availability.state === 'blocked') {
return <p>Sync unavailable: {tasks.availability.reason}</p>;
}
if (tasks.phase === 'error') return <p>{tasks.error?.message}</p>;
if (tasks.phase === 'ready' && tasks.rows.length === 0) return <p>Empty</p>;
return (
<ul>
{tasks.rows.map((task) => (
<li key={task.id}>
<button onClick={() => mutation.patch(task.id, { done: !task.done })}>
{task.title}
</button>
</li>
))}
</ul>
);
}Typegen puts these facts on the descriptor:
- a QueryIR-derived cache id, so SQL-only edits cannot reuse old state;
- exact table/scope dependencies for change routing;
- provable window coverage, claimed automatically while observed;
- a stable row key when the projection proves one.
useQuery returns { rows, phase, revision, isLoading, isRefreshing, error,
availability, refresh }. availability is the typed ready, migrating, or
blocked state shared by every client host. A schema reset that kept tables
reports ready; migrating means no synced table is readable yet. phase is:
loading: there is not yet a complete answer and there are no partial rows;partial: rows exist, but some required window coverage is incomplete;ready: the atomic snapshot says the answer is complete, including an honestly empty result;blocked: the tab cannot read through the browser leader, andavailability.reasonisleader-unreachable,leader-incompatible, orleadership-taken.isLoadingisfalse; previously read rows remain available for deliberate read-only UI. A schema block stops network transfer and leaves local reads running, so it appears inavailabilityand leavesphaseunchanged;error: the latest read failed. A refresh error keeps the rows and revision from the last successful read while settingisRefreshingtofalse.disabled: the hook was givenenabled: falseand reads nothing;rowsis empty andisLoadingisfalse.
Provider and async initialization
A ready client can be passed directly:
<SyncProvider client={client}><Tasks projectId="p1" /></SyncProvider>For async engines, create one resource outside React render. It owns one initialization attempt across StrictMode remounts, can retry a failed startup without replacing the provider, and closes the client exactly once when explicitly disposed:
import { createSyncClientResource, SyncProvider } from '@syncular/react';
const clientResource = createSyncClientResource(() => createClient());
<SyncProvider
client={clientResource}
fallback={<p>Starting local database…</p>}
renderError={(error, retry) => (
<div>
<p>{error.message}</p>
<button onClick={() => void retry()}>Try again</button>
</div>
)}
>
<App />
</SyncProvider>Call await clientResource.dispose() from the application's real lifecycle
owner, not from a StrictMode-sensitive child effect. Resource disposal and
provider-effect cleanup are safe in either order: provider teardown treats
window release as best effort when the owned client has already closed. Callers
do not need to stage a provider unmount before disposing its resource.
If the application requires authentication or signed quarantine processing
before protected data is visible, complete the concrete client's security
preflight before returning it from the resource factory. Do not mount the
ordinary provider tree while securityLifecycle is preflight: reactive store
startup intentionally touches protected status/outcome/query surfaces.
const clientResource = createSyncClientResource(async () => {
const client = await createClient({ securityPreflight: true });
await applyValidatedLocalPurge(client);
await client.activateSecurity({ encryption: acceptedKeyring });
return client;
});The normalized client exposes securityLifecycle(),
beginSecurityPreflight(), and keyless activateSecurity() for host-agnostic
coordination. Key-bearing activation stays on each concrete client type because
direct TypeScript uses an EncryptionConfig, while Worker/Tauri/React Native
use the portable keyring.
Use renderBoundary as the canonical application guard across browser and
native hosts. It covers resource startup/errors, migration, client upgrade,
server-behind, incompatible-schema, and unreachable-leader states. The
provider restores its children automatically when the public status becomes
ready again:
<SyncProvider
client={clientResource}
renderBoundary={(state, actions) => (
<SyncBlockedScreen state={state} onRetry={actions.retry} />
)}
>
<App />
</SyncProvider>fallback and renderError retain their existing behavior when
renderBoundary is absent. useSyncStatus() exposes the same classified
availability plus currentSchemaVersion, schemaFloor, and the raw status
fields for status chrome outside the provider guard.
The resource is stable across React remounts, not JavaScript module replacement. During development, preserve it in the bundler's hot-module data or dispose the old resource before creating another one. Otherwise the old worker and the new worker can briefly compete for the same persistent OPFS directory. Never wipe or rename the database in response to a retryable startup error.
For Vite, use createViteSyncClientResource(hot.data, schema.version,
createClient). It synchronously returns a pending-or-retained resource, keeps
a { schemaVersion, runtimeVersion, resource } record, reuses it for
same-schema HMR on the same published Syncular runtime, and sequences a
schema-bump or package-upgrade factory behind old-resource disposal. Await its
handoff promise before requesting hot.invalidate() when ownerChanged is
true. A failed handoff is also exposed by the resource through the ordinary
startup boundary and never opens a second owner. This recipe requires no
top-level await; the official example, optimizer exclusion, and upgrade
workflow are in the Vite guide.
retainViteSyncClientResource remains the async alternative for targets that
deliberately support top-level await. Either helper may close
the retained client before React runs cleanup for the old provider; Syncular
absorbs that teardown-only window-release race while still surfacing failures
from closing the resource itself.
useMutation
useMutation() retains the raw batch API. useMutation(generatedTable) adds
typed upsert, patch, and remove helpers:
const mutation = useMutation(tasksTable, {
onEnqueued(commitId) {},
onError(error) {},
});
await mutation.upsert({ id, projectId, title, done: false });
await mutation.patch(id, { title: 'Renamed' });
await mutation.remove(id);It returns pendingCount, isPending, error, and resetError. Overlapping
writes remain pending until all calls settle. Every method still returns a
promise and rejects on failure; callbacks do not replace error handling.
useRawSql
useRawSql(sql, params?, options?) is the read-only escape hatch for dynamic
SQL. It returns the same phase/revision result as useQuery.
const summary = useRawSql<{ total: number }>(
'SELECT count(*) AS total FROM tasks WHERE project_id = ?',
[projectId],
{
dependencies: [{ table: 'tasks', scopeKeys: [`project:${projectId}`] }],
},
);Options:
| Option | Meaning |
| --- | --- |
| dependencies | Exact table-associated dependencies. |
| coverage | Required window units read atomically with the rows. |
| rowKey | Stable identity fields used to retain unchanged row objects. |
| claimCoverage | Claim declared coverage while observed; default true. |
| publishFirstAnswer | Re-render for the revision of an empty answer with pending coverage; default false. |
| enabled | Disable observation and reads while false. |
| id | Stable cache identity for a raw query. |
| tables, scopeKeys | Compatibility shorthand; prefer dependencies. |
useRawSql reads no table names from the SQL text. Pass dependencies or
tables naming every table the statement reads; without either, the hook
throws a ClientSyncError with code client.raw_sql_dependencies_required
when it mounts. Generated queries are preferred whenever the statement is
known at build time because typegen derives the dependencies from the schema.
Exact changes and windows
Both cores emit one revisioned ClientChangeBatch per observer transaction.
Table changes keep scope keys associated with their table; window changes can
complete a zero-row unit without inventing a row change; status/conflict-only
batches do not rerun SQL. Bridges forward this batch unchanged.
Generated query coverage uses composable claims. Multiple consumers of the
same window base contribute a union, and unmounting one removes only its own
units. useWindow(base) remains the lower-level imperative interface for
prefetching or dynamic query builders. Applications normally do not need it
beside a generated useQuery. Its loaded field is false until the first
window-state read returns; until then units is empty whatever the window
holds. After a reload the store keeps every held unit until one of its claims
names it, so a query's claim never evicts units the app has yet to claim.
For a small known navigation working set,
useRetainedWindow(base, units) prefetches and retains those units through the
same coordinator. It returns { isPending, error }, normalizes duplicate
units, and releases only its own claim on unmount, so application code does
not need a custom retention effect.
Other hooks
useDiagnostics()observes the versioned, privacy-safe support snapshot. Native/Worker events trigger a fresh read on every host.useSyncStatus()observes the status domain without a follow-up read after every row change. It includesavailabilityandcurrentSchemaVersion;outboxis local push work, whilesyncNeededspecifically means an inbound pull/catch-up signal.useConflicts()observes conflicts and rejections only when that domain changes.useCommitOutcomes()observes the durable newest-first final-outcome journal from exactoutcomesChangedbatches. Resolve entries through the client returned byuseSyncClient().useCommitDelivery(ids)returns each listed commit's delivery status:pendingwhile the outbox holds it,knownwith its final outcome, orunknownwhen neither the outbox nor the journal holds the ID. It reads in onesnapshotReadand re-reads on outbox and outcome-journal batches.usePresence(scopeKey)observes ephemeral realtime peers.useSyncClient()anduseReactiveStore()expose the normalized low-level surfaces for integrations. When the concrete client was passed throughinstallRealtimeSupervisor()before mountingSyncProvider, its normalizeduseSyncClient()facade preserves supervisor observation: pass it directly torealtimeSupervisorSnapshot()andsubscribeRealtimeSupervisor(). Transport ownership and disposal remain on the concrete client/resource.
The hooks are SSR-safe: no local query runs during server rendering.
Router scheduling
Syncular hooks publish through useSyncExternalStore. If React Router owns
clinical query state, keep the router as the only owner and use its explicit
synchronous publication policy (<RouterProvider useTransitions={false}>) on
versions where sustained external-store updates can starve a transition. Do
not repair URL/render disagreement with window.location, flushSync, or a
mirrored store. The maintained fixture and upgrade guidance live in the
React guide.
Privacy-safe support view
Failed generated and raw live-query reads appear in
diagnosticsSnapshot().queryFailures until that query reads successfully.
Each entry contains only the stable PHI-free query id, generated table names,
a stable error code, an optional SQLite result code, and the first failure
time. It never contains SQL, parameters, rows, or SQLite error prose. Raw SQL
uses the diagnostic id raw unless useRawSql receives an explicit id.
The snapshot counts units by state (units.bootstrapping, units.complete,
units.reset, units.revoked, units.failed) and carries activeUnits and
the replica cursor, without scope values. The hook refreshes after diagnostics
events on direct, Worker, Tauri, and React Native hosts:
import { useDiagnostics } from '@syncular/react';
function SyncSupportPanel() {
const { snapshot, isLoading, error, refresh } = useDiagnostics();
if (isLoading) return <p>Collecting local sync evidence…</p>;
if (error) return <p>Diagnostics unavailable: {error.message}</p>;
return (
<section>
<button type="button" onClick={() => void refresh()}>
Refresh
</button>
<button
type="button"
disabled={!snapshot}
onClick={() =>
snapshot &&
void navigator.clipboard.writeText(JSON.stringify(snapshot, null, 2))
}
>
Copy support snapshot
</button>
<pre>{JSON.stringify(snapshot, null, 2)}</pre>
</section>
);
}The snapshot deliberately excludes scopes, rows, clinical counts, SQL, paths, identities, credentials, mutation bodies, stack traces, and arbitrary prose. Do not enrich the copied bundle with database files, query results, or console dumps. See SPEC §7.6 for the complete contract.
Query and window observers retain inactive entries only until the next
microtask. The final unsubscribe removes the entry from change dispatch
immediately; cleanup releases its rows and invalidates pending reads. A
same-microtask remount preserves the shared snapshot. A later subscription
starts a fresh read, including subscriptions held by an older React render.
Releasing the final window owner removes the empty claim group after the
core has applied the release. Disposing the store rejects unapplied retention
handles with client.reactive_store_disposed.
SyncProvider keeps the supplied client identity. useSyncClient() returns
that client, whose read methods can return either values or promises. Use
await client.statusSnapshot() in application code that supports multiple
hosts. The schemaFloor, leaseState, upgrading, and syncNeeded fields
come from that snapshot. Direct conflicts, rejections, and
securityLifecycle reads are now method calls. normalizeClient has been
removed; custom adapters must implement the canonical snapshot methods.
See the client migration.
Read the client with useSyncClient() at the top of a component, then call
client.proveCurrentBase(outcome) from a recovery handler. Every client host
exposes the same retained-base proof. Custom SyncClientLike implementations
provide the method and its typed result.
Live sync progress
useSyncProgress(client) subscribes to a direct, worker, Tauri, or React Native
client's live progress stream and returns SyncProgress | undefined. The hook
releases its subscription on unmount or when client changes. Download counters
use bytes; import counters use processed rows and can include uncommitted work.
See browser progress for
the attempt, phase, failure, and completion contract.
