React Integration
When a background request or another screen changes a profile, a React reader needs more than the promise returned by an imperative read. useQuery() reads through Suspense and subscribes to that key’s changes. A provider gives related screens a shared instance; Suspense handles waiting, and an error boundary handles rejected render reads.
The bindings require React and React DOM 19.2 or newer. They use use and useEffectEvent. This page starts with a complete local JSON app, then explains action, subscription, and resource lifetimes.
Build a working profile screen
Section titled “Build a working profile screen”Create a React TypeScript Vite application with a current Node.js LTS release supported by Vite:
npm create vite@latest query-react-demo -- --template react-tscd query-react-demonpm installnpm install @studiolambda/query react@^19.2 react-dom@^19.2 react-error-boundaryCreate public/profile.json:
{ "id": 1, "name": "Ada", "role": "Editor" }Replace src/App.tsx with this file. The instance is created once outside component render for this client-only application; server rendering requires a different, request-scoped owner.
import { Suspense, useState } from 'react'import { ErrorBoundary } from 'react-error-boundary'import { createQuery } from '@studiolambda/query'import { QueryProvider, useQuery } from '@studiolambda/query/react'
/** JSON representation served by public/profile.json. */interface Profile { readonly id: number readonly name: string readonly role: string}
/** One stable owner for this browser application's data. */const query = createQuery()
/** Renders resolved data and handles the explicit refresh action's rejection. */function ProfilePanel() { const { data, isPending, refetch } = useQuery<Profile>('/profile.json') const [message, setMessage] = useState('')
/** A user-requested refresh bypasses Query's valid cached value. */ async function onRefresh(): Promise<void> { setMessage('') try { await refetch({ fresh: true }) } catch (error) { setMessage(error instanceof Error ? error.message : 'Refresh failed') } }
return ( <section aria-busy={isPending}> <h2>{data.name}</h2> <p>{data.role}</p> <button disabled={isPending} onClick={() => { void onRefresh() }}> Refresh profile </button> <p role="status">{message}</p> </section> )}
/** Establishes cache, loading, and render-error boundaries before reading. */export function App() { return ( <QueryProvider query={query}> <ErrorBoundary fallback={<p>Profile unavailable. Reload the page to try again.</p>}> <Suspense fallback={<p>Loading profile…</p>}> <ProfilePanel /> </Suspense> </ErrorBoundary> </QueryProvider> )}Replace src/main.tsx to mount that named component:
import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import { App } from './App'
/** The mount element supplied by Vite's generated index.html. */const container = document.getElementById('root')if (container === null) throw new Error('missing root element')createRoot(container).render(<StrictMode><App /></StrictMode>)Run npm run dev -- --port 5173 --strictPort and open the profile screen. It displays Ada, Editor, and Refresh profile. Change the JSON role to Reviewer and click Refresh to see the new value. If the port is occupied, choose an available port in both command and URL. Stop the server with Ctrl+C when finished.
data is the resolved Profile, not a loading sentinel. The generic still does not validate JSON. isPending describes a React transition after the view can render; initial blocking loading belongs to Suspense. The awaited action is caught separately so a failed refresh can report a message while keeping the last value visible.
Choose the smallest hook for the task
Section titled “Choose the smallest hook for the task”All hooks obtain an instance from the nearest QueryProvider, unless you pass { query } explicitly. If neither exists, useQueryInstance throws the exported ErrNoQueryInstanceFound. A provider supplies the instance and UI policy, not a loading or error boundary.
| API | Use it when |
|---|---|
useQuery<T>(key, options) | You need resolved data, actions, and status hints |
useQueryBasic<T>(key, options) | You need only data and isPending; it still suspends |
useQueryActions<T>(key, options) | A control needs refetch, mutate, or forget without reading/subscribing to data |
useQueryStatus(key, { query }) | An indicator needs event/timer-derived status without initiating a read |
useQueryInstance({ query }) | Application code needs the raw instance |
useQueryContext() | An integration needs provider ContextValue directly |
useQueryTransitionContext() | An integration needs the current shared transition value |
ResourceOptions<T> and BasicResourceOptions<T> combine core read options with query, clearOnForget, and ignoreTransitionContext. Explicit hook settings override provider UI policy. An explicit instance overrides provider identity. Request options then fall back to that instance’s defaults.
Resource<T> combines BasicResource<T>, QueryActions<T>, and Status. The smaller hooks let an unrelated toolbar avoid subscribing to profile data it never displays. Action/status hooks are not non-Suspense data-reading alternatives.
For lower-level integrations, the package also exports Context with ContextValue, and TransitionContext with QueryTransitionContextValue. Rendering Context directly supplies values but does not acquire a provider’s incoming broadcast subscription. Prefer QueryProvider and QueryTransition in normal applications. Component prop types (QueryProviderProps, QueryTransitionProps, QueryPrefetchProps, and QueryPrefetchTagsProps) are exported for typed wrappers; QueryActionsOptions<T> and QueryInstance describe action-hook and explicit-instance options.
Refresh and edit with explicit outcomes
Section titled “Refresh and edit with explicit outcomes”refetch() defaults to stale: false, unless the hook’s read options override it. It still reuses an unexpired item and deduplicates eligible pending work. Use refetch({ fresh: true }) for a deliberate force-refresh, as in the application above. Action-specific options override hook options.
mutate(value, options) and forget() delegate to the corresponding key-bound core operations. Mutation expiration is supplied to that action; it does not inherit the hook’s fetched-value lifetime. Every action returns a promise and can reject. Do not leave a returned promise unhandled in a click handler.
For a server-backed edit, use the serialized server-write pattern. Display a pending form value with React’s useOptimistic if you need immediate feedback while the cache still holds server-confirmed data. Avoid overwriting the shared cache and restoring an old snapshot on failure when concurrent edits can occur; see optimistic recovery.
Recover from initial and background errors
Section titled “Recover from initial and background errors”Initial blocking read failures reject into the nearest error boundary. A failed or aborted observed background refresh keeps the last rendered value; observe the instance’s keyed error event for owning fetch failures. The explicit refetch promise still rejects and must be caught by its caller. This preservation rule is specific to refetch observers, not a promise that every failed mutation or clearOnForget transition is hidden from an error boundary.
Fresh initial failures retain their rejected resource selection. Resetting a boundary alone can select the same rejection. Invalidate the key before resetting it. In the app above, replace the boundary’s fallback prop with this fallbackRender prop:
fallbackRender={({ resetErrorBoundary }) => ( <button onClick={() => { void query.forget('/profile.json') .then(() => resetErrorBoundary()) .catch(console.error) }}> Retry profile </button>)}This is a JSX prop fragment, not a standalone component. query is the stable instance already defined in App.tsx. A successful retry renders the profile again; another failure returns to the boundary. Invalidation does not abort a still-pending transport. Use cancellation only if you own the shared work that should stop.
Understand fresh render lifetimes
Section titled “Understand fresh render lifetimes”useQuery(key, { fresh: true }) does not force a new request on every render. It uses the core resource() lifecycle so Suspense retries and same-key fresh siblings share one selected request. The first fresh reader chooses the options for that lifetime. Keep policies consistent across siblings.
Once consumers commit, effects retain the selection. The last consumer’s cleanup releases it on the next microtask; synchronous StrictMode reconnection can reuse it. A later mount after final release starts fresh again. Expiration alone does not retire a retained fresh selection.
A render that never commits has no committed cleanup. Its initial selection, including a rejection, remains available until forget, request/cache reconfiguration, or instance collection. This is why server requests need isolated instances and why retry must invalidate a failed fresh selection. Successful fetches, mutations, and hydration keep selected resources aligned with committed values. Explicit fresh actions can still replace requests; committed fresh readers keep successful data until a replacement succeeds.
For framework integrations, the core QueryResource<T> exposes promise and retain(). Call retain() only for a committed consumer and call its returned release function exactly once on cleanup. Ordinary non-fresh resources have no-op retention. Releasing does not forget data or abort transport. Ordinary imperative callers should use query(), not implement render retention themselves.
Control forgetting and conditional reads
Section titled “Control forgetting and conditional reads”By default, a mounted data hook keeps its displayed value when a forgotten event arrives. Setting clearOnForget on the provider or hook makes it select a replacement resource. The name does not mean that it blanks every screen or cancels work. A forget on a key without a stored item emits no event, so do not use it as a universal mounted reload signal.
There is no enabled, skip, null-key, or disabled-read option. useQueryBasic is also Suspense-based, and there is no shipped non-Suspense data hook. To wait until an identifier exists, conditionally mount a child component that owns the hook; do not conditionally call the hook inside one component:
/** Assumes ProfileDetails reads its required numeric id through useQuery. */function ProfileSelection({ id }: { readonly id: number | undefined }) { return id === undefined ? <p>Select a profile.</p> : <ProfileDetails id={id} />}ProfileDetails is your own component, with its boundary supplied by the parent. For a non-Suspense application, use imperative core reads and application-owned state/subscriptions, or choose a binding designed for that mode. The package does not turn undefined data into an implicit disabled state.
Coordinate transitions and interpret status carefully
Section titled “Coordinate transitions and interpret status carefully”Each data hook has a local transition by default. QueryTransition can share one useTransition() pair across related readers. With QueryTransition and React’s useTransition imported, wrap your existing reader tree:
/** Shares pending state across a group of query-driven updates. */function ProfileWorkspace() { const [isPending, startTransition] = useTransition() return ( <QueryTransition isPending={isPending} startTransition={startTransition}> <ProfilePanel /> </QueryTransition> )}Keep the provider and boundaries from the working app around this component. ignoreTransitionContext: true selects a hook’s local transition instead, and defaults to false.
The Status fields are UI hints, not a complete operation state machine:
expiresAtreads the local cached deadline, or current time if missing. Do not mutate the date.isExpiredbecomestruethrough a timer. The current implementation does not reset it tofalsewhen a later write extends expiration. Do not use it as an authorization or freshness gate.isRefetchingstarts onrefetchingand clears onresolved/error; it does not observeaborted, so it can remain set after cancellation.isMutatingis a boolean, not a count of queued mutations. A failed mutation emits no coreerror, so the hint can remain set until another relevant event.
Use action promises for completion and the core’s read policy for freshness. In particular, do not disable a critical recovery control solely because an event hint can remain set.
Refresh on browser events
Section titled “Refresh on browser events”There is no built-in focus, reconnect, or interval refresh. Own these listeners in one application-level lifecycle, rather than installing duplicate listeners in every reader.
This browser-only helper uses normal deduplication and skips valid cached entries. Import Query as a type from @studiolambda/query:
/** Owns one screen's refresh triggers without owning shared transport cancellation. */export function startProfileRefresh(query: Query): () => void { function refresh(): void { if (document.visibilityState !== 'visible') return void query.query('/profile.json', { stale: false, fresh: false }).catch(console.error) } window.addEventListener('focus', refresh) window.addEventListener('online', refresh) const timer = window.setInterval(refresh, 30_000) return function () { window.removeEventListener('focus', refresh) window.removeEventListener('online', refresh) window.clearInterval(timer) }}Call it in an owning effect and return its cleanup: useEffect(() => startProfileRefresh(query), [query]). Import React’s useEffect for that wiring. Cleanup stops triggers, not already-started shared requests. These examples do not require manual memoization or a consuming application’s React Compiler.
Provider unmount removes its incoming broadcast interest and reader effects remove their subscriptions. It does not abort requests, clear cache data, or close caller-owned channels. For optional warming use prefetching; for sharing event data between tabs, first read the broadcast isolation limits.