9.8. React Integration¶
@thekaveh/vmx-react is the official React 18 and React 19 adapter for
@thekaveh/vmx. It keeps React out of the language-neutral core while giving
applications a StrictMode-safe, server-rendering-safe external-store boundary.
Version 0.1.1 is published on npm.
9.8.1. Reactivity Primitive¶
The adapter uses React's useSyncExternalStore contract. A VmxStore owns one
lazy subscription to a VMx hub, exposes stable subscribe and cached monotonic
snapshot functions, and coalesces one synchronous hub drain into one React
invalidation. Subscribe-time catch-up closes mutations made while disconnected
or between render and commit. useVmx applies a selector with Object.is by
default or an explicit equality function such as shallowEqual.
9.8.2. Mapping¶
| React binding | VMx source |
|---|---|
createVmxStore / useVmx |
one shared IMessageHub selector boundary |
useVm |
every hub message sent by one VM, or by the VM a forwarding decorator wraps (needs 0.1.3; 0.1.1 re-renders on property changes only) |
useCommand |
ICommand.canExecuteChanged, stable execution, and an optional errors hook (needs 0.1.3) |
useParameterizedCommand |
canExecuteChanged for the parameter, stable execution, and an errors hook (needs 0.1.3) |
useVmChildren |
HierarchicalVM children snapshot, refreshed on add, remove, and reparent (needs 0.1.3) |
useObservableList / useVmCollection |
identity-preserving collection snapshots |
useDerivedProperty |
first and later derived values; unseeded state |
useAsyncResource |
discriminated async-resource state |
Text marked needs 0.1.3 describes the unreleased @thekaveh/vmx-react 0.1.3
source line. npm serves 0.1.1, so that text does not apply to the published
package.
9.8.3. Install And Create The Shared Store¶
npm install @thekaveh/vmx @thekaveh/vmx-react react rxjs use-sync-external-store
To start a new Vite app, use the React starter template in
starters/react-vite/. It was verified against
@thekaveh/vmx-react 0.1.1 and @thekaveh/vmx 3.30.0 from npm, with React 19.
From a VMx checkout, run
python3 tools/create-starter.py --channel react-vite. The command installs
the exact versions and checks for one React copy. It then builds the app and
drives it in headless Chromium.
To use an unreleased source line, follow the
pack-then-install source procedure;
do not link a live adapter checkout into a React 18 application. Apps moving
from local binding hooks or an older VMx line can follow
Upgrading TypeScript and React Consumers. The snippets
on this page use app, noteVm, workspace, screen, deleteNoteCommand,
note, folderNode, EditorVM, Editor, and EmptyEditor for your
application's own objects and components. Create one store at the application
composition root. The checked code on this page is tested with React 19.2.8, the
locked version in examples/typescript/react/notes-showcase:
import { createVmxStore, shallowEqual, useVmx } from "@thekaveh/vmx-react";
const store = createVmxStore(app.hub);
function Summary() {
const summary = useVmx(
store,
() => ({ title: app.model.title, busy: app.busy }),
shallowEqual,
);
return <p>{summary.title}{summary.busy ? "…" : ""}</p>;
}
Call store.dispose() only when the owning application scope is permanently
destroyed. React mount cleanup is managed by the hooks.
9.8.4. Focused Bindings And Conditional VMs¶
Use the narrowest binding that represents what the component renders:
const title = useVm(noteVm, vm => vm.model.title);
const save = useCommand(noteVm.saveCommand);
const notes = useVmCollection(workspace.notes);
const total = useDerivedProperty(workspace.total);
const resource = useAsyncResource(screen.data);
useCommand accepts an ICommand separately from its owning VM. Invoke the
stable callback returned by the binding; the equivalent direct VMx intent is
saveCommand.execute().
execute() of an AsyncRelayCommand returns before its task settles, so a
rejected task goes to the command's errors channel, not to the caller. Pass
onError (needs 0.1.3) to observe each failure while the component is
mounted:
const save = useCommand(noteVm.saveCommand, {
onError: (error) => showToast(`Save failed: ${String(error)}`),
});
The onError option needs 0.1.3. The hook subscribes to errors only when the
command has that channel and an
onError is given, and it unsubscribes on unmount. A command with no errors
channel, such as RelayCommand, binds as before. The hook always calls the
latest onError, so the function does not need to be memoized.
useParameterizedCommand binds a parameterized command to the parameter it runs
with, and useVmChildren returns a snapshot of a HierarchicalVM's children. Both hooks
need 0.1.3:
const del = useParameterizedCommand(deleteNoteCommand, note);
const kids = useVmChildren(folderNode);
useVm also re-renders a component bound to a forwarding decorator (needs
0.1.3). The
wrapped VM sends every hub message the decorator causes, so the hook matches
the senders that the decorator's wrappedBase chain reaches (ADR-0213).
ForwardingComponentVM works with every supported @thekaveh/vmx.
ForwardingCompositeVM needs @thekaveh/vmx 3.31.0, not yet on npm; 3.30.0
does not contain ADR-0213.
useDerivedProperty returns undefined until the property holds a value and
renders the first value as soon as a delayed source emits it. A
DerivedProperty stores its first value without a valueChanged emission
(DPROP-009), so the hook observes an internal @thekaveh/vmx seam that signals
the first value and every later change; it requires @thekaveh/vmx 3.24.1 or
later. The hook never subscribes to the property's sources, and unmounting
releases only its own listener; the property's owner disposes it.
const total$ = new Subject<number>();
const total = new DerivedProperty(total$);
function Total() {
const value = useDerivedProperty(total);
return <span>{value === undefined ? "Loading…" : value}</span>;
}
// Renders "Loading…" until total$.next(42), then "42".
A source that emits undefined as its value renders the same as an unseeded
property.
Never call a hook conditionally or pass null. Mount a child which owns one
unconditional binding when a VM is optional:
function MaybeEditor({ vm }: { vm: EditorVM | null }) {
return vm === null ? <EmptyEditor /> : <BoundEditor vm={vm} />;
}
function BoundEditor({ vm }: { vm: EditorVM }) {
const live = useVm(vm);
return <Editor title={live.model.title} />;
}
FormVM has no public hub, so useVm cannot bind it directly, and an approve
publishes nothing on the hub (spec/20 §8). Wrap the form in an application VM
that republishes its state, as the Notes showcase NoteFormVM does, or
subscribe in an effect to onApproved, approveErrors (approve failures),
and errorsChanged (validation errors).
9.8.5. StrictMode, SSR, Hydration, And Virtualization¶
The store connects on the first listener and disconnects on the last, including
React StrictMode's development remount. Create a store per server request,
render and hydrate from the same VM snapshot, and never share mutable server
stores between requests. getServerSnapshot does not subscribe during server
rendering.
Virtualized lists should bind once with useVmCollection or
useObservableList, use stable model keys, and pass item identities into rows.
Rows that display mutable VM state may call useVm locally.
9.8.6. Flagship And Release Policy¶
examples/typescript/react/notes-showcase/
is the Notes Workspace React 19 flagship. It consumes the official package
while keeping only application-specific browser adapters in the example.
The adapter follows independent SemVer under react-v* tags. Core releases do
not force adapter releases unless its public API or compatibility range changes.
See packages/react/RELEASING.md.
9.8.7. Serialize Portal Dialog Requests¶
Keep portal overlay state in an external observable store just like VM state,
but do not model it as one replaceable request slot. The flagship
ReactDialogService retains one active request and a FIFO queue. Each modal
resolver settles only its own promise and publishes the next request (or null)
to useSyncExternalStore. Explicit close uses the operation's neutral result
(false, null, or completion) and advances the same queue.
This is the queueing policy permitted by DIA-006. It prevents a second confirm,
file picker, or notification from replacing the active request and leaving the
first caller pending forever. See
ReactDialogService.tsx (examples/typescript/react/notes-showcase/src/views/adapter/ReactDialogService.tsx)
and its two-call settlement tests.