Skip to main content
useViewState stores one model-visible state object for each mounted view. Every component in that view reads and updates the same object.

Signature

Parameters

T | (() => T)
required
Initial state object or a lazy initializer. ChatGPT-restored state takes precedence over this value. When multiple components provide defaults, the first initialized default wins.
The state must be a JSON-serializable object. Arrays and primitives cannot be the root value. The reserved _uiContext key is managed by ModelContext and cannot appear in developer state.

Returns

useViewState returns a readonly [state, setState] tuple.
T
The current shared state for this mounted view. The internal _uiContext field is never returned.
(state: SetStateAction<T>) => void
Replace the object or update it from the latest shared value. The local update is synchronous and optimistic; host delivery continues asynchronously.

Share state across components

One mounted view owns one state object. Imported child components can call useViewState and receive the same value as the root component.
Separate view instances never share state.

Host behavior

The default object is delivered after the hook mounts, even if setState is never called.

Combine state with ModelContext

useViewState, <ModelContext>, and modelContext.set() share one model-visible snapshot. The serialized context tree is stored under _uiContext:
The host receives:
Every update sends the complete merged snapshot, so state changes preserve UI context and context changes preserve state.

Errors and delivery failures

setState throws when the next object contains _uiContext or cannot be serialized with JSON.stringify, such as an object containing a circular reference or bigint. Host delivery failures do not roll back the local state. The runtime logs a warning and keeps the latest snapshot ready to retry after the next state or context mutation.
  • Use ModelContext to describe what the user currently sees.
  • Use React useState for ephemeral values the model does not need, such as hover state.