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.
_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 calluseViewState and receive the same value as the root component.
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:
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.
Related
- Use
ModelContextto describe what the user currently sees. - Use React
useStatefor ephemeral values the model does not need, such as hover state.