React
Four hooks, one loading primitive, and types that make a loading waterfall or an unloaded read fail to compile rather than fail at run time. Everything on this page is the web client's binding (twinstate/react); the server and the protocol know nothing about React, components or URLs (see a native client).
Setup
tsx
<TwinProvider client={client} outbox={(o) => <OutboxSheet {...o} />}>
<App />
</TwinProvider>The provider only makes the client available; its value never changes, so it never re-renders the tree. Each hook subscribes on its own and re-renders its component only when its own result changes.
outbox is required. Some writes need a person: entries held after 24 hours, entries an upgrade made unsendable, and rejections that reached no mounted useMutation — made with client.mutate, resent after a reload or by a tab that adopted another's outbox, or answered after the component that made them unmounted. Held entries are a barrier — nothing behind them is sent until someone decides — so an app that forgot to show them would stall every later write, silently, a day later. The prop receives { held, fromOlderVersion, rejected, send, discard, copy } and renders whatever the app likes (see the client); leaving it out does not compile.
An app that would rather not ask anyone passes discard() (from twinstate/react), so the choice is written down where a reviewer sees it:
tsx
import { discard } from 'twinstate/react';
<TwinProvider client={client} outbox={discard({ onDiscard: (entries) => log(entries) })}>It renders nothing and decides at once, and what it decides is lost work: entries held past 24 hours are discarded (so the writes behind them flow), entries made by an older version are discarded instead of offered to copy, and rejections no mounted useMutation received are dismissed with no one told. onDiscard (optional) receives every entry and rejection that went — the only trace of them, so pass it if you log anything. (Inside a custom outbox UI, the prop's own discard field acts on one entry; it is unrelated to this import.)
Loading: entry and client.preload
A component that needs lazy data is an entry: it declares what it loads, and it can only be rendered with the result of client.preload, which starts those loads. Neither knows anything about routers or URLs.
tsx
export const NoteScreen = entry(
'noteScreen',
({ id }: { id: Id<'note'> }) => ({ body: noteBody(id) }), // what it loads, by name
function NoteScreen({ id, body }) {
// body: Loaded<'noteBody'>
return <Editor body={body} />;
},
{ absent: <NotFound /> }, // required: noteBody(id) can come back absent
);
const preloaded = client.preload(NoteScreen, { id }); // wherever navigation starts
<NoteScreen preloaded={preloaded} />; // the only way to render itclient.preload(Entry, props)starts the entry's loads and returns what rendering it needs. It is idempotent (same entry, same props: the same loads) and needs no matching "release": a preload that nothing renders expires after a TTL. So a navigation superseded half-way — three taps in quick succession — cannot leak anything. It is a method of the client, not of the component: wrappers such asmemocannot lose it, and there is no hidden global client.- An entry renders only with
preloaded, typedPreloaded<typeof NoteScreen>, and onlyclient.preloadof that entry produces one: the entry's type carries its name, so two entries with the same props still do not accept each other's. The entry's props come from the preload, so they cannot disagree with what was loaded. Rendering an entry that nothing preloaded does not compile, and the error reads as its fix:Property 'preloaded' is missing … { "start this entry's loads with client.preload(Entry, props) where navigation begins — a route loader, a click, a hover — or in the parent entry's loads": "noteScreen" }. - While mounted, an entry keeps its loads alive; unmounted, they are released after a grace period, so going back is instant.
- When a load counts as satisfied: its record has arrived; or the server has answered that it does not exist (
absent, below); or a pending mutation on this device produced it (a note created here, even offline, renders at once from its effect, and the subscription catches up when the connection does). With the persisted cache, a cached record also satisfies a load. - Until then, the entry renders its
fallback(entry(name, loads, Component, { fallback }),nullby default) and its component does not render at all. - A handle always points at a record. If a load comes back
absent, the entry renders itsabsentelement instead of its component, souseShared(body)is typed as the record, nevernull.absentis required exactly when a load can be absent — a by-id load not wrapped inmaybe— and not accepted otherwise (a single lazy value always exists, adefaultedrecord exists whenever its parent does, and a query window is never absent): a deleted note can never be left showing a spinner. A load for which "not there" is normal is declaredmaybe(…)—({ result: maybe(exportResult(jobId)) }), an export's output, which does not exist until its job finishes — and only its handle reads asT | null.
The arguments stay positional — name, loads, component, options — because TypeScript infers the component's handle props from loads left to right: in a single object literal, writing component before loads would silently widen them.
Where preload is called
tsx
// a hover warms it; the click that follows gets the same load, already under way
<Link to={`/notes/${id}`} onPointerEnter={() => client.preload(NoteScreen, { id })} />
// an overlay: the trigger starts the load and opens with the result
<button onClick={() => openOverlay(client.preload(Details, { id }))}>Details</button>
// a nested entry: the parent's loads start the child's, in parallel with its own
entry('thread', ({ id }: { id: Id<'conversation'> }, { preload }) => ({ transcript: transcript(id), details: preload(Details, { id }) }), …)Preloads are keyed by the entry itself and its props, compared by value (as TanStack Query compares its keys). So the hover's preload(NoteScreen, { id }) and the navigation's, a moment later, are the same load: the second returns the one already under way, or finished, and the entry renders without a fallback flash. Two entries never share a preload, even if they share a name — checkEntries fails on duplicate entry names anyway, because tests key their fixtures by name.
With a router
A router needs two things to host an entry: code that runs on navigation, before render (a loader, beforeLoad, a resolver, a history listener) to call client.preload, and a way to hand its result to the component. What matters is that the two are paired soundly — the component must receive the result of its route's preload, not something a type assertion claims it is.
| router | how the pairing is made | helper needed |
|---|---|---|
| TanStack Router | the loader and the component are on one route object; Route.useLoaderData() is typed from that object's own loader | none |
| React Router, framework mode | the preload goes in the route module's clientLoader (a loader runs on the server, where there is no twin client and the result is serialized), and typegen derives Route.ComponentProps['loaderData'] from it | none |
| React Router, data mode | useLoaderData<typeof loader>() is a type assertion — nothing ties it to the route's loader — so write both fields with one small helper of your own (below) | yours, ten lines |
| no loaders (wouter, a hand-written router) | every navigation goes through one open(Entry, props) that preloads, then changes the URL, keeping the result with the address state; the history listener does the same for back/forward and deep links | none: the type flows through |
ts
// TanStack Router (a route file)
export const Route = createFileRoute('/notes/$id')({
loader: ({ params }) => {
const id = parseId(note, params.id);
if (!id) throw notFound(); // TanStack's notFound() is thrown, not returned
return client.preload(NoteScreen, { id });
},
component: () => <NoteScreen preloaded={Route.useLoaderData()} />,
});
// React Router, data mode — with the helper below, written once in your app
createBrowserRouter([
twinRoute(client, NoteScreen, {
path: '/notes/:id',
props: ({ params }) => {
const id = parseId(note, params.id);
if (!id) throw data(null, { status: 404 }); // React Router's 404: a thrown response
return { id }; // typed from NoteScreen's props
},
}),
]);twinRoute is not part of Twinstate (a package helper may come when an app needs one); it returns an ordinary route object:
ts
import { createElement } from 'react';
import { useLoaderData, type LoaderFunctionArgs, type NonIndexRouteObject } from 'react-router';
import type { TwinClient } from 'twinstate/client';
import type { Entry, Preloaded, PropsOf } from 'twinstate/react';
export function twinRoute<E extends Entry>(
client: TwinClient,
entry: E,
{
path,
props,
...rest
}: Omit<RouteObject, 'loader' | 'Component'> & {
path: string;
props: (args: LoaderFunctionArgs) => PropsOf<E>; // typed from this entry
},
): NonIndexRouteObject {
return {
...rest,
path,
loader: (args) => client.preload(entry, props(args)), // before render, on navigation and deep links
Component: () =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- the loader above is this route's own
createElement(entry, { preloaded: useLoaderData() as Preloaded<E> }),
};
}Its one assertion — useLoaderData() is otherwise any, which typescript-eslint's no-unsafe-* rules reject — is written once, with its reason on the disable comment, and is always true: the same call wrote the loader it reads. If every data-mode route goes through it, it is the only assertion in your routes. It is one route per call, not an array, so each route's props is typed from its own entry; nested routes are children: [twinRoute(…)]. The pattern is Relay's entry points, where a route declares its entry point and a helper generates the loader and the component (@loop-payments/react-router-relay's preparePreloadableRoutes).
What the types guarantee, precisely: rendering an entry that nothing preloaded does not compile — provided the route is paired soundly (one of the table's rows), casts are banned, and any cannot flow in. Twinstate's lint preset turns on the last two with typescript-eslint's no-unsafe-type-assertion (any narrowing assertion, so {} as Preloaded<…> and 'n1' as Id<'note'>), no-unsafe-assignment and no-unsafe-argument (an any reaching a prop or an argument). They apply to the whole codebase; an app adopting them gradually gets twinstate/no-brand-cast meanwhile, which bans casts to Twinstate's own brands only. Tests make values with testId and testPreload, never casts.
The one wrong place is during render, which would start the load after rendering began. Two lint rules in Twinstate's preset catch it, the way React's rules-of-hooks work, from the code's structure:
twinstate/no-preload-in-render: aclient.preloadwhose nearest enclosing function is a component or hook body, or a callback given touseEffect,useLayoutEffect,useMemoor auseStateinitialiser, is an error. Inside any other nested function (anon*handler,useCallback, a media-query listener), in a route loader, or in an entry's loads, it is allowed — those run on intent, not on render.twinstate/preload-before-await: aclient.preloadafter anawaitin the same function is an error — start it first, so the two run in parallel (a load that truly depends on the result disables the rule on that line, with a reason).
Indirection a lint rule cannot see (a helper called during render that calls preload) is caught by checkEntries: in tests the client knows when React is rendering, and a preload started then fails, naming the entry. Production checks nothing.
Reading: useShared
tsx
function NoteList() {
const notes = useShared((s) => s.note.sorted(byRecent)); // instant kinds: select anything, always present
…
}
const b = useShared(body); // a lazy root, through the handle its entry received- The selector form reads
instantkinds. They are on the device from startup, so it never loads and never fails. Lazy kinds are not in its state type: you cannot reach a note body through a selector. - The handle form reads one lazy root, with its
reffields resolved (body.imagesis an array of image records, delivered with the body) and its children as ordered arrays — or a query's window. A handle —Loaded<'noteBody'>— is made only by an entry, for a load it declared, so reading lazy data nobody loaded does not compile.useSharedkeeps the handle's load alive while it is mounted, so a handle can never point at data that is gone. - Children take the handle as a prop (
function Images({ body }: { body: Loaded<'noteBody'> })) and read it themselves, so a parent does not re-render when only a child's fields change — the same reason Relay passes fragment references rather than data.
Both re-render only when their result changes (zustand selectors over useSyncExternalStore). A selector must return a stable value: one that builds a new array or object on every call does not merely re-render too often — React reports an infinite loop ("getSnapshot should be cached"). The memoised helpers (s.note.sorted(byRecent), with a comparator defined at module level) and useShallow are the ways to derive, and the twinstate/stable-selector lint rule rejects a selector that returns an array or object literal, a spread, or a .map/.filter/.sort result without them.
Is this live? useSyncStatus
ts
const { state, asOf } = useSyncStatus(); // the whole app: 'live' | 'stale' | 'outdated' | 'incompatible' | 'protocolError'
const { stale } = useSyncStatus(body); // one load, through its handleData is stale while disconnected, and, with a persisted cache, from startup until a topic's resume or reset has arrived; asOf is when it was last live. incompatible means this bundle cannot read what the server now sends (see running clients); what to show and whether to reload is the app's onIncompatible. outdated means a newer version is open on this device, so this tab stopped and is read-only (see the client). protocolError means a frame the server could not act on — a bug, not a deploy. Reads themselves never change shape: useShared returns cached and live records the same way.
This is the one signal for "what I show may be out of date", whatever the cause. A screen where acting on stale data could mislead — "is this turn still running?" — reads it and annotates or disables itself; one that must not show anything unconfirmed renders its own placeholder while stale. Its loads have already started, so waiting costs no waterfall, and the server remains the guard: an action taken on stale data is checked when it arrives.
Writing: useMutation
ts
const [pin, { pending, error }] = useMutation(twin.mutations.pinNote);
pin({ id, pinned: true });Calling it writes to the outbox, shows the effect immediately, and sends. The returned pending covers "not yet confirmed by the server"; error is the rejection, typed as the mutation's declared reasons plus invalid, unavailable and error — or, refused locally because this tab has stopped and is read-only, outdated (a newer version is open on this device) or incompatible — for an inline message. Outside React, client.mutate(twin.mutations.pinNote, args) does the same. pending ends when the server has accepted the mutation; an outcome that comes later (a payment settling) is state on a record, so the component renders it, and imperative code awaits it with client.until (see the client).
A text field bound to a mutation needs nothing special:
tsx
const b = useShared(body);
const [save] = useMutation(twin.mutations.updateNoteBody);
<textarea value={b.text} onChange={(e) => save({ id: b.id, patch: { text: e.target.value } })} />;Every change is written to the outbox at once and shown at once; patches to the same field merge until you pause (300ms), so the server sees one write per pause; a kill loses at most the change still being written (milliseconds), and backgrounding the app flushes it first.
Events: useEvent
ts
useEvent(twin.events.notice, (n) => playSound(n)); // in every open tab
useEvent(twin.events.notice, (n) => showToast(n), { perDevice: true }); // once per deviceEvents the server emits (see concepts), delivered with a topic's changes to the clients holding it — the instant topic, unless emitted on a lazy root — and replayed after a short gap (up to the event's maxAge); the payload is typed by the registry.
UI state: useState
Hover, a menu being open, a gesture in progress — plain React, untouched. State that belongs to one device (a theme) is not Twinstate's concern; the optional twinstate/device utility covers it. The one thing not to do is copy shared state into useState to edit it; bind the field to a mutation instead (above).
Different screens, different amounts
instant data is the same on every device — only what every screen needs. What differs per device is which entries are open, and so what lazy data is loaded. A column that only a wide screen shows is its own entry, a sibling of the main one, preloaded by the same navigation code that already knows the layout:
ts
function open(id: Id<'conversation'>) {
const thread = client.preload(Thread, { id });
const activity = wide.matches ? client.preload(ActivityColumn, { id }) : null; // the layout's own media query
setAddress({ id, thread, activity });
}
wide.addEventListener('change', () => {
/* preload the column when the screen widens; drop it when it narrows */
});A phone never loads data for a column it does not show, and nothing is loaded during render. Rotating to wide shows the column's fallback briefly while it loads. Query windows keep one size everywhere (first: 50), and a small screen simply scrolls further with loadMore: the size is not part of a query's identity, so it is not worth splitting preloads by device. Preloading on hover is per device too — useful with a pointer, pointless on a phone. What stays out of bounds is a kind that is instant on one device and lazy on another — it would break the rule that a read's type says whether it can be missing.
Why there are no waterfalls
A waterfall is sequential: B cannot start loading until A's data has said B exists, or until A has rendered. Each kind is closed by the types.
Data waterfalls — A's data contains an id, and a component uses it to load B.
- A
refis delivered with the record that refers to it and comes back resolved, so following arefnever loads anything. - A
linkresolves only to the target's instant record; its lazy data loads only when you navigate to it (a new entry), never inline. - Loading needs a branded
Id<K>, and a lazy read needs a handle, which only an entry's declared load produces — so a component cannot quietly load something on its own.
Render waterfalls — a component that loads B is only mounted after A has loaded:
tsx
if (!a.ready) return <Spinner />; // children below mount later…
return <B />; // …so B would start loading lateAn entry cannot start its own load when it mounts: it can only render with a preloaded, which something produced before rendering — a route loader, an event handler, or its parent entry's loads, which run in parallel with the parent's own. A nested entry nobody planned for does not compile; one preloaded during render is a lint error. How early loading starts — on click, or already on hover — is a product choice, and a one-line one.
Disjoint data is not a waterfall. An entry that shows a note and, say, system stats declares both; they load side by side.
A native client
Entries and preload are the web binding's shape of one portable idea: a screen declares what it needs, and opening it starts loading before it renders. The server only ever sees "this connection subscribes to topic X". A native client (Swift, Kotlin) would speak the protocol directly, re-implement the client core (replica, apply, outbox) with the same semantics, and express entries as its own screens or navigation destinations — nothing about routes or URLs. What it would need that does not exist yet: the registry exported as JSON Schema, and a protocol conformance suite runnable against any client.