@smart-code-solutions/suspense-live-query
v0.6.0
Published
Function-first React 19 Suspense resources with optional live query adapters for Convex and Firestore.
Readme
@smart-code-solutions/suspense-live-query
React 19 Suspense resources with a ReactFire-style preload/read split.
Agent adoption skill
Use $use-suspense-live-query to integrate this library into another repository.
The versioned instructions live in skills/use-suspense-live-query/SKILL.md
and are included in the package tarball. They cover session identity, scoped
preloads, hook migration, SSR auth, and real-consumer validation.
Install the whole use-suspense-live-query folder in your Codex skills directory
(usually ~/.codex/skills) for use across repositories. A symlink to this checkout's
folder keeps a local installation in sync; copying the folder from an installed
package gives you instructions matching that package version. Restart or refresh
skill discovery if an already-open chat does not see it.
A consuming repo can add this narrow instruction to its AGENTS.md:
When adopting or changing suspense-live-query usage, use the
use-suspense-live-queryskill. Preserve our auth boundary and verify the affected feature; do not replace unrelated Convex hooks.
Install
Core only:
npm install @smart-code-solutions/suspense-live-query reactConvex adapter:
npm install @smart-code-solutions/suspense-live-query react convexFirestore adapter:
npm install @smart-code-solutions/suspense-live-query react firebaseThe intended app shape is:
await preloadThing(args);
navigate("/destination");const thing = useThing(args);Preload and destination reads share the same warmed resource. Direct refresh still works because the destination read starts the resource if it was not preloaded.
Firestore
import {
preloadFirestoreDoc,
preloadFirestoreDocData,
useFirestoreDoc,
useFirestoreDocData,
preloadFirestoreQueryData,
useFirestoreQueryData,
} from "@smart-code-solutions/suspense-live-query/firestore";Warm a document before navigation, then read the same live document on the destination page:
await preloadFirestoreDocData(playerRef);
navigate(`/players/${playerId}`);function PlayerPage({ playerRef }: { playerRef: DocumentReference<Player> }) {
const player = useFirestoreDocData(playerRef);
return <h1>{player?.name}</h1>;
}If constructing the ref is async, preload can take a provider function:
await preloadFirestoreDocData(async () => {
const db = await getReadyFirestore();
return doc(db, "players", playerId).withConverter(playerConverter);
});The destination hook still receives the concrete ref. The ref's Firestore instance and path are used as the default cache identity, so the preload and hook share the same live document entry.
Converters are optional. If you use .withConverter(), the model type is inferred. You can also pass a generic assertion or a parse function.
const player = useFirestoreDocData(playerRefWithConverter);
const player = useFirestoreDocData<Player>(rawPlayerRef);
const player = useFirestoreDocData<Player>(rawPlayerRef, {
parse: (data) => PlayerSchema.parse(data),
});Convex
Mount the bridge inside your Convex auth provider. Pass the signed-in user's stable ID
(or null after sign-out), and wait for authentication to settle before rendering
private queries. Changing this identity remounts the resource subtree with a fresh cache.
Do not reuse a static session key between accounts.
<ConvexSuspenseBridge sessionKey={user?.id ?? null}>
<Suspense fallback={<Loading />}>
<App />
</Suspense>
</ConvexSuspenseBridge>The bridge is required for these hooks. Inside it, use usePreloadQuery() or
usePreloadPaginatedQuery() for scoped navigation preloads. Imperative-only users
must call setConvexClient(client, userIdOrNull) before reads and on every identity
change. Never configure a process-global client for authenticated SSR requests;
use the server-only convex/nextjs entrypoint instead.
Conditional queries accept "skip": useQuery(query, ready ? args : "skip")
returns undefined when skipped and starts no watch. Skipped pagination returns
empty, exhausted results. Query arguments and pagination items are inferred from
the Convex function reference.
Live pagination delegates cursor management and page reconciliation to Convex.
It requires Convex 1.41 or later in the 1.x series and uses the SDK's internal
watchPaginatedQuery method; compatibility is checked against the installed SDK
in the real-consumer test. The legacy cursor field is always null because the
SDK owns cursors. loadPrevious() rejects because Convex pagination is forward-only.
import {
ConvexSuspenseBridge,
preloadQuery,
useQuery,
preloadPaginatedQuery,
usePaginatedQuery,
} from "@smart-code-solutions/suspense-live-query/convex";await preloadQuery(api.players.get, { playerId });
navigate(`/players/${playerId}`);const player = useQuery(api.players.get, { playerId });Preload, navigate, read
The default remains the ReactFire pattern. The preload and destination use the same generated query, arguments, client, and session cache, including when local loading/error boundaries surround the destination:
const preload = usePreloadQuery();
async function openPlayer(playerId: Id<"players">) {
await preload(api.players.get, { playerId });
navigate(`/players/${playerId}`);
}
// At the destination; continues receiving live updates:
const player = useQuery(api.players.get, { playerId });Or start preloading and navigate immediately, letting destination Suspense show loading; handle the preload promise's rejection in the initiating event. A preload awaits the first value, and its watch remains warm for the unused-entry retention window (60 seconds). Mounted readers retain it. Use a retained reference below when loading code/routes may take longer. Preloads are optional: direct navigation starts the same resource. Calls through stale preload callbacks throw after session teardown.
Shared session, local recovery
Put one bridge above the authenticated app. Use ordinary local Suspense and error
boundaries underneath it; another cache per screen is unnecessary. Convex hooks
always select the bridge's cache, even inside a generic SuspenseCacheProvider.
That is a behavior change for consumers that previously relied on nested providers
to clear failed Convex queries.
Use the optional framework-neutral QueryBoundary once in your app's feature
wrapper. Pass your component directly; it receives { error, retry } and may
use hooks. The nearest boundary catches a failed reader. Its retry restarts only
that caught failed resource, then resets its own UI, even after the reader unmounted.
Healthy sibling queries, drafts and pages remain mounted.
import { QueryBoundary, type QueryBoundaryErrorProps } from
"@smart-code-solutions/suspense-live-query/convex";
function QueryError({ error, retry }: QueryBoundaryErrorProps) {
if (isAuthError(error)) throw error; // your existing auth authority
return <button onClick={retry}>Try again</button>;
}
<QueryBoundary loading={<Loading />} ErrorComponent={QueryError}>
<ProfileEditor />
</QueryBoundary>For static error UI, use errorFallback={<Text>Could not load.</Text>} instead.
ErrorComponent and errorFallback are mutually exclusive. Static error UI has
no retry callback and cannot route particular errors outward; use ErrorComponent
when recovery or auth classification is needed. Neither prop is the loading UI.
The boundary adds no cache and is usable with native or web ReactNode UI. Omit
loading to let a surrounding/router Suspense handle loading; pass loading={null}
to intentionally hide it. A named fallback component preserves its local state
across parent updates. A fallback that throws reaches the outer boundary. Put
independent features in sibling boundaries when their state must survive each
other's failures. A failure still unmounts the children of the boundary that caught
it; this cannot preserve a draft inside that failed subtree.
For an existing custom error boundary, keep the lower-level useQueryRecovery():
call retry(caughtError) before its resetErrorBoundary(). It returns the number
of current failed resources restarted; zero can mean a non-query error or eviction.
Neither API automatically retries writes. Mutation errors go to the form's
onError; preserve its draft and let the user submit again. A mutation succeeding
updates live queries through Convex without a manual query retry.
The bridge now waits for its cache owner to commit before admitting readers and
blocks them after effect cleanup, including hidden Activity. Pass
fallback={<Loading />} on the bridge for this admission interval and SSR.
Caller-supplied generic caches keep their caller-owned lifecycle and can render
seeded data during SSR. Bridge-owned SSR renders its admission fallback without
starting authenticated client watches; use the
existing server preload helpers for server-rendered data. Authentication must
still remove private readers before changing the SDK identity. A cache key is
not an auth transport synchronization mechanism.
Pause new requests
Set paused on ConvexSuspenseBridge or SuspenseCacheProvider to block new
library-owned request starts in that cache without changing its identity:
<ConvexSuspenseBridge sessionKey={user.id} paused={needsUpdate}>
<App />
</ConvexSuspenseBridge>New reads/preloads suspend or wait until resumed; matching cached reads still work.
Existing live subscriptions and in-flight requests continue normally. This is
admission control, not a transport shutdown: SDK reconnects, server pagination
reconciliation, native SDK hooks, usePreloadedQuery, and calls outside this
library are not intercepted. Local cache writes remain available. Apply props
through React and start imperative work from events or passive effects.
Library useMutation/useAction return { status: "paused" } without dispatch,
pending work or callbacks. Refused writes are never queued or replayed. Writes
already sent retain their normal completion/error outcome and lifetime guards.
Convex and Firestore pagination loadMore/loadNext (and Firestore loadPrevious) reject with RequestsPausedError if a new page
would be requested; callers handle the refusal and may try again after resuming.
Optional Convex background prefetch skips this refusal without failing the reader;
it can attempt again on a subsequent page/live update or reader interaction.
Imperative owners can call const resume = cache.pauseRequests() and later
resume(); cache.requestsPaused reads committed admission state. Leases compose:
all must release before queued reads start, and releasing twice is harmless.
Disposal removes queued reads and rejects their promises. Unused queued entries
still follow normal cache GC. A nested generic cache does not unpause the Convex
session. Keep any app-owned version/refresh control outside its paused cache so
it can continue to check readiness; version comparison and reload policy belong
to the application.
Retained query references and fragments
Use references when a route explicitly owns a preload or passes a live reader to children. They supplement the simpler preload-then-navigate API:
const [playerRef, loadPlayer, disposePlayer] = useQueryLoader(api.players.get);
// In an event or passive effect:
const reference = loadPlayer({ playerId }); // starts immediately
await reference.ready; // optional before navigation
// In a child beneath Suspense:
const player = useQueryReference(playerRef);loadQuery(useConvexEnvironment(), query, args) is the imperative equivalent;
its caller must call reference.dispose(). Loader hooks release their previous
reference on replacement and their owned reference on unmount/hidden Activity.
Disposal releases retention, not other readers or the shared cache; unused entries
then follow normal GC. Reference readers reject disposed references and references
from a different bridge, including A → B → A. Do not load in render or layout
effects; events and passive effects run after session admission. Keep a loader
above the destination's Suspense boundary. References are client objects, not
serializable server payloads.
const playerName = defineFragment(api.players.get, player => player?.name ?? "");
function Name({ playerRef }) {
const name = useFragment(playerName, playerRef);
return <span>{name}</span>;
}Define stable fragments outside render. defineFragment(query, select, isEqual?)
is a typed selector over that query's result. It shares the native watch, and
Object.is (or your equality function) suppresses updates when selected data is
unchanged. It does not generate a server projection or normalize entities. Pass a
non-null reference; the parent decides whether the child exists. Plural data is
ordinary arrays in the query result or separate child readers.
useRefetchableFragment(fragment, reference) returns [data, refetch].
refetch(args) selects those complete generated arguments and returns a promise
for the restarted query. useRefetchQuery(query) restarts a query without a
fragment. Live updates already happen automatically; neither is required after a
mutation. Restarting a Convex watch may immediately return SDK-cached data; this
is not a network-only fetch guarantee.
Pagination and forward prefetch
The existing usePaginatedQuery(query, args, { initialNumItems }) is the simplest
live list API. loadPaginatedQuery(environment, query, args, options) returns an
owned pagination reference. usePaginationFragment(reference) reads that same
list and adds refetch(args, options?), which restarts only the selected page
resource and resets its forward window, even with identical arguments. Call
reference.dispose() when its owner is done.
usePrefetchableForwardPaginationFragment(reference, { bufferSize }) keeps a
hidden live prefix buffer. loadNext(count) reveals buffered rows and awaits any
additional required rows (or exhaustion); background prefetch does not set the
visible loading indicator. Live edits/deletes/reordering come from Convex's page
engine. Refetch resets the visible count to the requested initial size. All page
readers sharing exactly the same resource share its loaded pages, so explicitly
restarting that resource resets those readers together. Different arguments and
other resources are unaffected. No backward pagination or fabricated cursors are
provided.
Mutations with UI bookkeeping
const [save, isInFlight] = useMutation(api.profiles.updateProfile);
function submit() {
void save({ displayName }, {
onCompleted: saved => { setDisplayName(saved.displayName); setMessage("Saved."); },
onError: () => setMessage("Could not save. Try again."),
});
}
<button type="submit" disabled={isInFlight}>Save</button>Execution and optimistic transactions use the native Convex SDK. useMutation
executes every call independently, including overlapping calls with identical
arguments. Each call has its own promise, outcome, and callbacks. isInFlight
stays true until all pending calls from this hook instance settle. The hook accepts
optional optimisticUpdate; it does not coalesce, queue, abort, or retry writes.
Forms use isInFlight to disable Submit while saving. This is a user-experience
control, not a security or server idempotency guarantee: clients can bypass it.
The server must enforce authorization and business rules, including duplicate
protection when repeating an operation would be harmful.
The same hook handles intentional overlapping writes, such as a bulk action:
const [deleteItem, isInFlight] = useMutation(api.items.remove);
const outcomes = await Promise.all(selectedIds.map(id => deleteItem({ id })));
// Inspect each outcome when reporting partial failure.Ordinary mutation error outcomes do not reject Promise.all.
Migrating from 0.2: the default remains concurrent. Remove the singleFlight
option, and use the form's pending/disabled controls to prevent repeat submissions
through its UI. There is one mutation hook for both forms and bulk actions.
The promise resolves to { status: "success", value }, { status: "error", error },
{ status: "inactive" }, or { status: "paused" }. Use callbacks for component UI effects: they run only
while that hook lifetime remains active, and are suppressed after unmount,
Suspense/Activity layout cleanup, or session change. Callbacks are synchronous UI
effects: synchronous exceptions reject the promise, but returned promises are not
awaited and their continuations are not lifetime-protected. A callback can throw
after the server write succeeds; rejection is not permission to retry the write.
Keep drafts, messages, navigation, and validation in the feature.
Checking a returned outcome does not make arbitrary later async work
session-safe. Suppressing a completion does not cancel the server operation.
The library adds no write retry; the SDK retains its own transport retry and
exactly-once guarantees. Native convex/react mutations remain supported, and
SDK execution remains authoritative.
If Activity hides and reveals a form while its write is still pending, the hook keeps tracking that write until it settles. The old lifetime's callbacks stay suppressed and its outcome is inactive. Any new call after reveal is independent.
Action data: preload, navigate, read
Use actionQuery when a Convex action fetches data, such as an external search.
It declares read intent; it cannot verify that the server action is read-only.
Create the descriptor outside render. Creating it does not execute the action.
import { actionQuery, usePreloadQuery, useQuery } from
"@smart-code-solutions/suspense-live-query/convex";
export const searchResults = actionQuery(api.search.external);
// In the navigation owner:
const preload = usePreloadQuery();
await preload(searchResults, { term });
navigate(`/results?q=${encodeURIComponent(term)}`);
// On the destination, beneath Suspense:
const results = useQuery(searchResults, { term });Preload and destination share the same session cache entry for the action name
and generated arguments, including across separate descriptors and nested generic
providers. Direct navigation starts the fetch if necessary; "skip" starts none.
The imperative preloadQuery and preloadQueryWithClient also accept descriptors,
with the same explicit session/SSR constraints as other imperative preloads.
Preload resolves the raw result or rejects with its error. Navigation after an
await still belongs to the screen's own async lifetime guard.
Action data is a one-time response, not a live subscription. It stays cached while
readers are mounted and follows the usual 60-second unused retention window.
useRefetchQuery(searchResults) explicitly fetches a replacement. A caught data
error stays cached until explicit refetch, targeted QueryBoundary retry, or
eviction; there is no automatic retry. Refresh/eviction/direct reads can execute
the action again, so do not wrap commands such as sending email or charging a card.
Late responses after restart or session disposal cannot repopulate the old entry;
this does not cancel an already-dispatched action.
Retained references, fragments, pagination, subscriptions, and entry-point query
specifications keep their existing live-query contracts in this version. Native
server Preloaded payloads remain separate; action descriptors are client data
descriptions, not server hydration payloads.
Imperative actions with UI bookkeeping
import { useAction } from "@smart-code-solutions/suspense-live-query/convex";
const [sendEmail, isSending] = useAction(api.email.send);
void sendEmail({ recipient }, {
onCompleted: () => setMessage("Sent"),
onError: () => setMessage("Could not confirm sending"),
});useAction has the same commit/pending tuple, generated types, synchronous
callbacks, and success/error/inactive outcomes as useMutation. Every call runs
independently; pending stays true until all calls settle. Calls do not warm or
modify actionQuery data. The same unmount/Activity/session callback guards apply.
Actions have no optimistic update option and no added automatic retries. An error
or suppressed completion does not prove an external effect never happened; the
wrapper supplies neither cancellation nor exactly-once execution guarantees.
Subscriptions, local state, and entry points
useSubscription(query, argsOrSkip, { onNext, onError }) observes the shared query
in an effect without suspending its component. Both callbacks are required;
updates use the latest callbacks and stop on cleanup or session change. This is
for side effects. Rendering live data normally uses useQuery; all Convex query
reads already subscribe.
useClientQuery is an alias for core useValue: pass a suspensifyStore or other
local resource, not a Convex function. This supplies Relay's local-data use case
without pretending Convex has a separate normalized client schema.
const playerEntry = {
load: () => import("./PlayerRoute"),
queries: (playerId: Id<"players">) => ({
player: querySpec(api.players.get, { playerId }),
}),
};
const [entry, loadEntry, disposeEntry] = useEntryPointLoader(playerEntry);
// event: loadEntry(playerId)
// render beneath Suspense:
<EntryPointContainer entryPointReference={entry} props={{ title: "Player" }} />
// PlayerRoute receives { queries: { player: QueryReference }, props: { title } }.loadEntryPoint(environment, definition, params) starts the dynamic import and
all declared query loads together; the caller owns disposal. Import failure
releases the references and is thrown to the boundary; load a new entry point to
retry the import. Hook replacement/unmount
releases its owned entry. Compose nested entry points at their route owners;
there is no Relay compiler-generated route manifest. Query specifications are
created with querySpec(query, args) to retain generated argument checking.
Try the hooks and adapt a real feature
Run npm run dev:playground in this checkout and open http://127.0.0.1:4173.
Every new Convex hook has an interactive panel with delays, failures, live edits,
account switches, Activity hide/show, subscription counts and disposal controls.
This uses actual public hooks with a controlled SDK-shaped client, not a live
Convex deployment. Playground coverage lists each hook,
its panel/test, and the server/transport limits. npm run check:playground runs
Chromium interactions and records evidence under ignored validation/playground/.
Checked examples adapt actual EasyGov cases, BoardSense
review/chunk queries and WYA profile forms. They also cover session/auth boundaries,
targeted retry, route entry points and the native server-preload contract. They
are shipped in the package and compiled by npm run check:examples. EasyGov and
BoardSense examples are patterns, not claims those applications have migrated.
Core consumers can use useValueIn(cache, resource, ...args) for explicit owners,
useValueSelectorIn(cache, resource, select, isEqual, ...args) for equal-selection
render suppression, and retainIn(cache, resource, ...args) for explicit retention.
observeIn(cache, resource, callback, ...args) delivers queued ResourceSnapshot
values and returns an unsubscribe; cache disposal also suppresses queued callbacks.
Callback exceptions remain application errors, not shared query errors.
retryErrorIn(cache, caughtError) restarts matching current errors that were thrown
by readers and returns their count. Convex consumers normally use the scoped hooks.
Relay API correspondence
| Relay feature | Convex adaptation |
| --- | --- |
| RelayEnvironmentProvider, useRelayEnvironment | ConvexSuspenseBridge, useConvexEnvironment |
| useLazyLoadQuery | useQuery / useLazyLoadQuery alias; always live |
| loadQuery, useQueryLoader, client usePreloadedQuery | loadQuery, useQueryLoader, useQueryReference |
| useClientQuery | Local core resource read; no Convex watch |
| useFragment, useRefetchableFragment | Typed selectors over a shared query reference |
| usePaginationFragment | Native live forward pagination reference |
| Experimental usePrefetchableForwardPaginationFragment | Buffered prefix of that native live list |
| useMutation | Typed commit/pending tuple with SDK optimistic updates |
| Convex action execution | useAction; same UI bookkeeping, no optimistic update or automatic retry |
| Data fetched by a Convex action | actionQuery with usePreloadQuery / useQuery / useRefetchQuery; one-time cached results |
| useSubscription | Effect observer of the same shared query |
| useSubscribeToInvalidationState | No normalized record invalidation state exists; observe live query results or explicitly retry a failed resource |
| useMutationAction_EXPERIMENTAL | Compose the typed mutation tuple with React Actions; distinct from Convex useAction, with no Relay transaction runtime |
| loadEntryPoint, useEntryPointLoader, EntryPointContainer | Parallel code and typed query preloads |
GraphQL compiler features (masking, generated fragment keys, directives,
normalized-record updaters, fetch policies, deferred graph fields) do not have
honest one-to-one Convex equivalents. Use generated Convex functions to control
server query shape, native optimistic updates for writes, and React Suspense /
transitions for rendering. This API covers the React workflows, not Relay's
GraphQL runtime. The native SDK's server Preloaded / usePreloadedQuery
contract below is unchanged and remains distinct from client query references.
Design references: ReactFire preload/read source, Relay hook APIs, and Convex React.
For Next.js Server Components, use the server-only Convex subpath to create a serializable payload, then read it in a Client Component:
// Server Component
import { preloadQuery } from "@smart-code-solutions/suspense-live-query/convex/nextjs";
export async function PlayerWrapper({ playerId }: { playerId: string }) {
const preloadedPlayer = await preloadQuery(api.players.get, { playerId });
return <PlayerClient preloadedPlayer={preloadedPlayer} />;
}// Client Component
"use client";
import {
type Preloaded,
usePreloadedQuery,
} from "@smart-code-solutions/suspense-live-query/convex";
function PlayerClient({
preloadedPlayer,
}: {
preloadedPlayer: Preloaded<typeof api.players.get>;
}) {
const player = usePreloadedQuery(preloadedPlayer);
return <div>{player?.name}</div>;
}For less repetition, hide the Preloaded type in a domain module:
// players.server.ts
import { preloadQuery } from "@smart-code-solutions/suspense-live-query/convex/nextjs";
export function preloadPlayerForClient(playerId: string) {
return preloadQuery(api.players.get, { playerId });
}
export type PreloadedPlayer = Awaited<
ReturnType<typeof preloadPlayerForClient>
>;// players.client.ts
"use client";
import {
usePreloadedQuery,
useQuery,
} from "@smart-code-solutions/suspense-live-query/convex";
import type { PreloadedPlayer } from "./players.server";
export function usePlayer(playerId: string) {
return useQuery(api.players.get, { playerId });
}
export function usePreloadedPlayer(preloaded: PreloadedPlayer) {
return usePreloadedQuery(preloaded);
}Pagination follows the same shape:
await preloadPaginatedQuery(
api.messages.list,
{ channelId },
{ initialNumItems: 25 },
);const { results, loadMore, hasNext, status } = usePaginatedQuery(
api.messages.list,
{ channelId },
{ initialNumItems: 25 },
);Domain Resources
Use the core primitives to build small domain APIs, then keep the primitive resource private.
import { preload, suspensify, useValue } from "@smart-code-solutions/suspense-live-query";
const userResource = suspensify(fetchUser);
export function preloadUser(userId: string) {
return preload(userResource, userId);
}
export function useUser(userId: string) {
return useValue(userResource, userId);
}Callsites stay shaped like the adapters:
await preloadUser(userId);
navigate(`/users/${userId}`);const user = useUser(userId);Sync values that become ready later should also be wrapped behind a domain API:
import {
preload,
suspensifySync,
useValue,
} from "@smart-code-solutions/suspense-live-query";
const authUserResource = suspensifySync(() => auth.currentUser, {
isReady: (user) => user !== undefined,
subscribe: (notify) => auth.onAuthStateChanged(notify),
});
export function preloadAuthUser() {
return preload(authUserResource);
}
export function useAuthUser() {
return useValue(authUserResource);
}Mutable or device-backed resources should get the same treatment:
import {
preload,
refresh,
setValue,
suspensifyStore,
useValue,
} from "@smart-code-solutions/suspense-live-query";
const notificationPermissionResource = suspensifyStore(checkPermissions, {
initialValue: "checking",
});
export function preloadNotificationPermissions() {
return preload(notificationPermissionResource);
}
export function useNotificationPermissions() {
const status = useValue(notificationPermissionResource);
async function requestPermissions() {
setValue(notificationPermissionResource, "checking");
const nextStatus = await requestNotificationPermissions();
setValue(notificationPermissionResource, nextStatus);
}
return {
status,
denied: status === "denied",
granted: status === "granted",
requestPermissions,
recheckPermissions: () => refresh(notificationPermissionResource),
};
}Core Primitives
The root package has no Firebase or Convex dependency. Use these primitives to build adapters and domain APIs:
import {
clear,
createSuspenseCache,
invalidate,
preload,
refresh,
reload,
setValue,
suspensify,
suspensifyExternalStore,
suspensifyStore,
suspensifySync,
usePreload,
useValue,
} from "@smart-code-solutions/suspense-live-query";Default cache identity is:
resource function identity + stable serialized argumentsManual keys are an escape hatch for non-serializable arguments, intentional cache sharing, or SDK-specific identity.
Scoped Caches
The global cache is the default. Use SuspenseCacheProvider only for scoped caches, such as SSR requests, tests, multiple app roots, or multiple clients.
const cache = createSuspenseCache("request-123");
<SuspenseCacheProvider cache={cache}>
<App />
</SuspenseCacheProvider>;If you use a scoped cache and want imperative preloads to hit that same scoped cache, call usePreload() inside the provider instead of the global preload() function.
Cache lifetime and refresh
Unused resources are retained for 60 seconds, including abandoned preloads.
gcTimeMs overrides this retention window; live updates do not extend it.
Mounting a reader cancels eviction, and its last unmount starts a new window.
Preloads and suspended reads that have not committed must finish within that
window; increase it for slow sources. ttlMs separately controls result freshness.
Owned providers dispose their caches on unmount; callers supplying cache own
its disposal. Scope authenticated data to the session, and SSR data to the request.
reload, invalidate, and clear restart mounted resources in place so readers
stay subscribed. Unmounted entries are removed. refresh rereads synchronous
sources and restarts live subscriptions; callbacks from the old subscription are ignored.
In a provider, use the *In(cache, ...) operations or scoped hooks rather than global operations.
Publishing
The source repository remains private. npm releases are public and include only
the package's files allowlist (dist, skills, and examples), plus npm's standard metadata
and README/LICENSE. The package is licensed under MIT. Review
npm pack --dry-run before publishing.
The package name is @smart-code-solutions/suspense-live-query, under the
smart-code-solutions npm account. Before the first publication, verify that the
name remains available and authenticate locally with npm login as that account;
do not put npm credentials in this repository. The release workflow rejects the
original placeholder scope.
For the first release, run npm ci, npm run check, and npm pack --dry-run,
inspect the tarball, then deliberately bootstrap the package with
npm publish --access public from a clean, reviewed commit on main. This initial
publish uses your npm account and its required authentication/2FA. An existing
package is needed to configure the publisher in its npm settings.
If GitHub Actions is deliberately enabled for a future release, configure npm's
trusted publisher with owner
smart-code-solutions, repository suspense-live-query, workflow filename
release.yml, no environment name, and permission for direct npm publish.
Complete its first workflow publish within two days of configuring it; otherwise
recreate the expired configuration. See npm trusted publishing.
For subsequent releases, update the manifest and lockfile version, merge the
reviewed change to main, and create/push its v<version> tag. GitHub Actions is
currently disabled; do not enable or dispatch it as part of a local release.
Authenticated local publication is supported: check out the reviewed tag on a
clean tree, run npm ci and npm run check, inspect npm pack --dry-run, then
publish with npm publish --access public --provenance=false. The tagged version
must match the manifest and belong to origin/main. Use the npm account's required
authentication/2FA; keep credentials out of the repository. After success, verify
the registry version and record the release with
gh release create v<version> --generate-notes.
The retained release.yml workflow is an alternative only if GitHub Actions is
explicitly re-enabled and its trusted publisher is configured. It checks the exact
version tag against origin/main, runs all checks, inspects the package, and
publishes using OIDC. Do not dispatch it while Actions is disabled.
This private repository's package is published without a source provenance attestation. Publishing does not deploy or upgrade any consuming application.
Verification
npm run check runs TypeScript checks, React lifecycle/adapter regressions,
compiled examples, Chromium playground interactions, and packed-package installation
tests with optional adapters installed separately. Install Chromium once with
npx playwright install chromium when the local browser is missing.
The runtime tests include mocked Convex watches and offline Firestore; they are
focused tests, not proof of a deployed application. Live consumer validation must
also cover navigation, mutations reflected across tabs, pagination, and account switching.
Real WYA consumer check
tests/fixtures/wya-consumer.patch records the tested integration against WYA
commit 7ffd171. Apply it in an isolated WYA checkout, install this package's
npm pack tarball in apps/web and packages/notes, and start the web app with
NEXT_PUBLIC_SITE_URL=http://localhost:3001 bun run dev --port 3001.
Use that checkout's existing development environment files; do not deploy its backend.
The runner permits only the verified fine-manatee-368 development deployment.
From this library checkout, run:
WYA_ROOT=/absolute/path/to/isolated-wya node scripts/check-wya-consumer.mjsThis creates synthetic accounts and notes through the actual UI, verifies live
updates across tabs, loads another page, navigates away/back, switches accounts
in the same browser document, and deletes the created notes. Screenshots and
results are saved under ignored validation/wya/; test credentials are saved
there with owner-only permissions for recovery. Accounts remain on the development
backend. To repeat without creating more accounts, set WYA_CREDENTIALS to a
previous run's .credentials.json and use a fresh VALIDATION_OUTPUT directory.
The integration uses a page size of two and an auth-session boundary. It also removes the sample web form's redundant callback URL, which otherwise redirects to the backend's Expo origin. This validates the real Next.js Notes consumer and Convex backend, not WYA's shipped Expo app or EasyGov's filing journey.
Performance traces
Opt in with a stable recorder per app/request. No events or telemetry are sent by default. Do not create a new recorder on each render.
import { createPerformanceRecorder, SuspenseWithPerf } from
"@smart-code-solutions/suspense-live-query";
const recorder = createPerformanceRecorder({ maxEvents: 200, userTiming: true });
// Inside the existing Convex/auth provider:
<ConvexSuspenseBridge sessionKey={userId} performance={recorder}>
<SuspenseWithPerf name="sharing-settings" recorder={recorder} fallback={<Loading />}>
<SharingSettings />
</SuspenseWithPerf>
</ConvexSuspenseBridge>Core callers use createSuspenseCache("app", recorder) or the performance prop
on an owning SuspenseCacheProvider. A supplied cache owns its own recorder.
Provider/bridge recorders are selected when the cache is created; changing this
prop does not reset an active cache or its queries. Keep the recorder stable.
Custom resources accept a static name option. Adapter resources use their kind
as a label; opaque resourceId distinguishes entries without exposing arguments.
recorder.getEvents() returns a copy of the newest bounded events, oldest first;
JSON.stringify(recorder.getEvents()) is the test attachment/export format.
recorder.clear() clears events and owned browser measures. The playground's
Performance traces panel displays these events, and its browser check writes
validation/playground/performance.json alongside the test receipt.
Events have kind (resource/fallback), name, opaque traceId, optional
resourceId, phase, timestampMs and durationMs. Timestamps use the runtime's
monotonic performance clock where available; durations are elapsed since the
attempt started, not individual network latency. New source attempts get new
trace IDs; the entry ID persists across restarts. Phases are start, first-result,
update, error and end. End reasons distinguish restart, pause, disposal and
fallback cleanup. First-result can be an SDK cache hit, not a network response.
Fallback cleanup includes hide/unmount and StrictMode effect replay; it is not
a successful reveal or paint measurement. Transitions that retain content may
show no fallback. Error events carry no error message or payload.
Optional onEvent(event) runs asynchronously; throwing/rejected reporting never
changes query results. The application owns batching, sampling, release/platform
metadata, storage, retention and dashboards. No SDK or backend is required.
Callbacks already queued can still report an earlier event after disposal/clear.
Use static non-sensitive labels; arguments, results, user IDs, cache names and
credentials are not included automatically. No global recorder is installed.
userTiming adds bounded browser measures for non-start events (inspect their
detail in Performance tools); clear/eviction removes only this recorder's
measures. Missing User Timing APIs are tolerated on native/SSR. Measurements
cannot separate server processing from transport or replace React Profiler.
Production telemetry integration, native-device validation and consumer adoption
are separate from this library's controlled browser proof.
