Developer guide
Portable React components: controlled state and durable data
Design React bricks with clear controlled and uncontrolled APIs, synchronous snapshots, and separate cloud persistence adapters.
Draft preview — this article has not been published.
By ELFUpdated Evidence reviewed
The most useful boundary in a portable React library is between who owns a value and where that value is saved. Controlled or uncontrolled describes ownership in the component tree. Durable or temporary describes storage lifetime. Those are independent decisions.
Documentation reviewed November 7, 2026. The contracts below are original design examples. They are not a platform SDK and do not claim that a database or a live host integration has already been implemented.
Begin with an explicit view contract
React's state-sharing guidance describes controlled components as driven by props and uncontrolled components as retaining their own state. Lifting a value to the appropriate parent makes that parent its authority. React: sharing state between components
For a library, a controlled view and a small local wrapper make this distinction easy to see:
import { useState } from "react";
type CounterProps = {
value: number;
onValueChange: (next: number) => void;
disabled?: boolean;
};
export function Counter({ value, onValueChange, disabled }: CounterProps) {
return (
<button
type="button"
disabled={disabled}
onClick={() => onValueChange(value + 1)}
>
Count: {value}
</button>
);
}
export function LocalCounter({ defaultValue = 0 }: { defaultValue?: number }) {
const [value, setValue] = useState(defaultValue);
return <Counter value={value} onValueChange={setValue} />;
}
Counter has no opinion about a host or database. LocalCounter owns its state for the current mount. A persisted controller can also render Counter while loading and saving through an adapter. The same controlled view works in all three cases.
For richer components, expose intent instead of forcing consumers to reverse-engineer a replacement object. onToggleItem(id) and onRenameItem(id, title) carry clearer domain meaning than a generic onChange(unknown). Keep purely visual values, such as an open accordion, independent from business commands when they need different lifetimes.
A React store must expose a synchronous cached snapshot
useSyncExternalStore reads through getSnapshot and subscribes through subscribe. React requires the snapshot to remain the same value while the store has not changed. An immutable snapshot should be replaced only when its contents change. The subscription returns cleanup. Server rendering additionally needs a matching server snapshot. React: useSyncExternalStore
Use a contract like this at the React boundary:
type Snapshot<T> = Readonly<{
value: T;
phase: "loading" | "ready" | "saving" | "error";
revision?: string;
error?: string;
}>;
type SnapshotStore<T> = {
getSnapshot: () => Snapshot<T>;
subscribe: (listener: () => void) => () => void;
};
getSnapshot() returns a value already held in memory. It does not return a promise, create a fresh object on every call, fetch data, or write defaults. The controller loads asynchronously, validates the result, replaces the cached snapshot, and then notifies listeners.
This is especially important for host integrations. An adapter can accept asynchronous messages while the component still reads synchronously. Do not try to unify both operations into getState(): T | Promise<T> and pass that function directly to React.
Keep the persistence port separate
The following is an application contract for a backend you control:
type Revisioned<T> = { value: T; revision: string };
type DurablePort<T, Command> = {
load: (signal?: AbortSignal) => Promise<Revisioned<T>>;
execute: (
request: {
command: Command;
expectedRevision: string;
mutationId: string;
},
signal?: AbortSignal
) => Promise<Revisioned<T>>;
};
The expectedRevision lets an implementing server reject a stale edit. mutationId lets an implementing server recognize a retried operation. Neither field has magical semantics: the backend must enforce both, scope them to the authorized document and actor, and document retry behavior.
If a host only accepts snapshots without revisions, give it a different port with weaker capabilities. Do not invent revisions in the browser and call the result conflict-safe. A server receipt, a host setter call, and a local state update are different outcomes.
Define the mutation policy before making it optimistic
For a first durable implementation, serialize mutations per document and return the authority's accepted snapshot. This gives the controller a straightforward rule for which revision is current. Disable or queue dependent actions while required data is loading.
If you add optimistic rendering, keep confirmed state and pending commands separate. After a successful response, update confirmed state and replay any remaining compatible commands. After a conflict, fetch the current record and either reapply a safe command or ask the user to resolve an ambiguous change.
Do not replace the current view with an old response simply because that request happened to finish last. Request identity, document identity, and revision belong in the controller's acceptance logic. A component unmount should unsubscribe its view without silently canceling a mutation the product already promised to save; define that lifecycle deliberately.
Treat initialization and migration as data operations
Defaults are for absent state. They are not a repair strategy for every invalid response. Distinguish these cases:
| Incoming condition | Recommended behavior |
|---|---|
| No record exists | Create or display defaults according to the authority's initialization contract. |
| A valid empty record exists | Preserve the user's empty value. |
| A known older schema exists | Apply a tested migration and persist it through the normal authority. |
| A newer schema exists | Preserve it and show upgrade-required or read-only behavior. |
| Data is malformed | Report the problem and retain evidence; do not overwrite it automatically. |
Include schema version and stable record identity in stored data. Avoid using a component's render order, array index, or bundle hash as a record identifier.
Make compatibility a matrix of capabilities
Our recommended library vocabulary separates memory state, host-restorable view state, documented host persistence, and application-owned durable storage. Add explicit capabilities for tool calls, external navigation, or realtime subscriptions only when the adapter implements them.
A controller may support load and execute in a Site, but only local commands in a native visualization. The view can still be shared. A missing persistence capability should change the product promise and interaction, not disappear behind a no-op function.
For verification, test the risks this architecture introduces: delayed hydration, duplicate mutations, out-of-order responses, failure and retry, incompatible schemas, and listener cleanup. Test actual reopen and multi-client behavior before advertising cloud synchronization. See the OpenAI surface comparison and Hatch guide for the host-specific boundaries.