Skip to Content
HooksuseShareableViewerState

useShareableViewerState

Save and restore a complete viewer configuration as JSON, an inline URL, or an application-owned short link. Existing camera/visibility/selection links remain readable. Complete snapshots include binding materials, textures, decals, transforms (including pivots/shear), actions and metadata. Pass configuration to also include model sources, scene settings, variant choices, section cuts, isolation, multi-selection, annotation filters and the active annotation.

Complete configuration example

Keep the props you want to save controlled. The hook cannot inspect changes kept privately inside a viewer. This example connects scene settings, isolation, annotations, bindings, selection, and camera, and offers JSON download/import.

configuration-sharing.tsx
"use client"; import { useState } from "react"; import { DEFAULT_SCENE_CONFIG, MAX_VIEWER_STATE_BYTES, ModelViewer, serializeViewerState, useShareableViewerState, useViewerCamera, useViewerSelection, type ViewerConfiguration, } from "@liveroom-tech/react-immersive"; import type { ObjectBinding } from "@liveroom-tech/react-immersive"; export function ConfigurationViewer({ licenseKey, modelUrl, }: { licenseKey: string; modelUrl: string; }) { const [configuration, setConfiguration] = useState<ViewerConfiguration>({ modelUrl, sceneConfig: DEFAULT_SCENE_CONFIG, isolation: null, activeAnnotation: null, annotationCategories: null, }); const [bindings, setBindings] = useState<Record<string, ObjectBinding>>(); const [isReady, setIsReady] = useState(false); const [error, setError] = useState(""); const camera = useViewerCamera(); const selection = useViewerSelection(); const report = (error: unknown) => setError(String(error)); const sharing = useShareableViewerState({ cameraState: camera.cameraState, setCameraState: camera.setCameraState, objectBindings: bindings ?? {}, onObjectBindingsChange: setBindings, selectedObjectBinding: selection.selectedObjectBinding, setSelectedObjectBinding: selection.setSelectedObjectBinding, configuration, onConfigurationChange: (next) => { if (next.modelUrl !== configuration.modelUrl) setIsReady(false); setConfiguration(next); }, isReady, autoSync: false, onError: report, }); async function saveJson() { setError(""); try { const state = await sharing.getStateAsync(); const blob = new Blob([serializeViewerState(state)], { type: "application/json", }); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = "viewer-configuration.json"; anchor.click(); setTimeout(() => URL.revokeObjectURL(url), 0); } catch (error) { report(error); } } return ( <> <button disabled={!isReady} onClick={() => { setError(""); void sharing .createShareUrl() .then((url) => navigator.clipboard.writeText(url)) .catch(report); }} > Copy configuration link </button> <button disabled={!isReady} onClick={() => void saveJson()}> Save JSON </button> <label> Load JSON{" "} <input type="file" accept=".json,application/json" onChange={(event) => { const file = event.target.files?.[0]; event.target.value = ""; if (!file) return; if (file.size > MAX_VIEWER_STATE_BYTES) { report("Configuration exceeds 5 MiB."); return; } void file.text().then(sharing.restoreState).catch(report); }} /> </label> {error && <p role="alert">{error}</p>} <div style={{ height: 600 }}> <ModelViewer {...configuration} licenseKey={licenseKey} objectBindings={bindings ?? "auto"} onObjectBindingsChange={setBindings} selectedObject={selection.selectedObjectBinding} onObjectSelect={selection.handleObjectSelect} onCameraChange={camera.handleCameraChange} onSceneConfigChange={(sceneConfig) => setConfiguration((old) => ({ ...old, sceneConfig })) } onIsolationChange={(isolation) => setConfiguration((old) => ({ ...old, isolation })) } onActiveAnnotationChange={(activeAnnotation) => setConfiguration((old) => ({ ...old, activeAnnotation })) } onAnnotationCategoriesChange={(annotationCategories) => setConfiguration((old) => ({ ...old, annotationCategories })) } onModelLoaded={() => setIsReady(true)} onViewerReady={(ready) => { camera.handleViewerReady(ready); void sharing.restoreFromUrl().catch(report); }} refitOnResize={false} tools={{ section: true, isolate: true }} /> </div> </> ); }

await getStateAsync() returns a detached snapshot with live texture, decal, background and annotation-image blobs embedded as data URLs. This includes local preview files registered under logical material paths. Save serializeViewerState(await sharing.getStateAsync()) in a file or your own persistence layer and restore its JSON with restoreState(json).

getState() remains synchronous for configurations that already have portable asset references. It reports a clear error if an image needs async capture. prepareViewerState(input, baseUrl?) provides async image capture without the hook; parseViewerState(input) validates already-portable data. These utilities are exported from the main entry and /utils.

Multiple models

Include the current modelUrl, models, mergeModels, and active sceneConfig in configuration. Each model entry includes its own bindings, scene settings and merge-source prefixes. Write binding changes back to the active entry, as shown in multiple-model usage . Apply onConfigurationChange to the same state that supplies these props; this callback replaces the configuration rather than patching it. Keep isReady false while a restored active model or its sources load. Staged restoration resumes when readiness/configuration changes or restoreFromUrl() is called again from onViewerReady. The saved camera is applied after configuration.

The configuration type also supports modelFormat, tilesetUrl, backgroundColor, shadows, cinematic, cameraControllerType, objectTransformSpace, arScaleMode, and usdzUrl. It also includes saved measurements and calibration from sceneConfig.measurements, or the explicit measurements, measurementSettings, measurementUnit, and measurementModelId configuration fields. License keys, callbacks, React overlays, raw Three.js objects, transient animation playback positions, and unsaved measurement picks are not serialized. The active annotation identifies the current tour stop; it does not start or resume tour autoplay.

For large configurations, provide a ViewerStateStorage adapter:

import type { ShareableViewerState, ViewerStateStorage, } from "@liveroom-tech/react-immersive"; const storage: ViewerStateStorage = { async save(state: ShareableViewerState) { const response = await fetch("/api/configurations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(state), }); if (!response.ok) throw new Error("Could not save configuration"); const result: { id: string } = await response.json(); return result.id; }, async load(id) { const response = await fetch( `/api/configurations/${encodeURIComponent(id)}`, ); if (!response.ok) throw new Error("Configuration is unavailable"); return response.json(); }, };

Pass storage and normally autoSync: false to the hook. Then await sharing.createShareUrl() saves a detached snapshot and returns #viewId=...; restoreFromUrl() loads that ID through the adapter. The endpoint above is an application example, not a service supplied by this SDK. Implement access, retention and asset hosting in your application. A recipient needs the same storage adapter. Storage failures reject the operation; newer incoming links supersede older pending requests.

createShareUrl() automatically captures live images before saving/linking. getShareUrl() and syncUrl() are synchronous and require portable asset references; use the async methods when temporary images are present. They always use inline JSON. Inline URLs are limited to 65,536 characters by default; maxUrlLength can change this guard, but an application/browser/link-sharing service may impose a smaller limit. JSON state is limited to 5 MiB, including when loaded from storage. Autosync reports errors through onError and never overwrites an incoming link while restoration waits for configuration, models or bindings.

Parameters

NameDescription
cameraState, setCameraStateCurrent camera and instant restore handler from useViewerCamera. A failed/not-ready camera returns false and is retried later.
objectBindings, onObjectBindingsChangeCurrent active-model bindings and their setter. Complete snapshots replace the binding map.
selectedObjectBinding, setSelectedObjectBindingCurrent selection and setter. Also pass selectedObject to the viewer.
configuration, onConfigurationChangeOptional ViewerConfiguration and replacement setter. The callback is required when restoring a snapshot that includes configuration.
isReadyDefaults to true; pass false while restored assets load.
mode"configuration" captures full bindings and supplied configuration. This is the default when configuration is supplied; otherwise the default is compact "view" mode (camera, hidden IDs and selection).
storageOptional ViewerStateStorage for async short links.
maxUrlLengthMaximum inline URL length; default 65536.
onErrorBackground errors; direct API calls reject/throw to their caller. Without a handler, background errors are logged.
paramKeyDefault "view"; stored-link IDs use viewId (or ${paramKey}Id). Other hash parameters are preserved.
debounceMsAutosync debounce; default 400 milliseconds.
autoSyncDefault true. Starts after an initial URL read/full restore; false leaves sharing explicit.

Returns

NameSignatureBehavior
getState() => ShareableViewerStateReturns a detached version-1 snapshot.
getStateAsync() => Promise<ShareableViewerState>Returns a portable snapshot, including live local images.
restoreState(input: unknown) => Promise<boolean>Validates/restores JSON or parsed state; false while pending. No address-bar change.
getShareUrl() => stringBuilds an inline link without changing the page URL.
createShareUrl() => Promise<string>Uses storage when supplied, otherwise inline JSON.
syncUrl() => voidWrites an inline link with history.replaceState.
restoreFromUrl() => Promise<boolean>Restores a new link; repeated ready callbacks do not reapply the same snapshot.

Compatibility and assets

  • Unversioned links containing camera, hidden IDs and selection still work, including automatic bindings that become available after the model loads.
  • For compact links that omit materials and metadata, use mode: "view". Configuration mode includes all binding data. Existing callers that omit both configuration and mode keep compact links. To save full bindings without model/scene props, explicitly pass mode: "configuration".
  • Relative model, texture, annotation-image/link and environment paths become absolute against the sender’s page URL. HTTP(S) assets and embedded image data URLs are supported. Original model files are not bundled.
  • Temporary texture/decal/image blobs are embedded automatically by getStateAsync() and createShareUrl(). Their original files do not have to be uploaded to a server. Captured image data survives a reload or another device opening the configuration. The live bindings and preview stay intact.
  • Embedded images count toward the 5 MiB JSON and inline URL limits. For large images use Save JSON, a storage adapter for a short link, or a durable image URL from onTextureUpload. An unavailable/revoked temporary image produces a clear error asking you to reload or reselect it.
  • Model files and custom HDR/EXR environments are not embedded. Those assets still need durable HTTP(S) URLs; this remains a configuration save, not a full model-file archive.
  • Save original assets for animations. A configuration describes the viewer’s data; it is not a GLB export, an asset archive, or a license grant.
  • Invalid JSON, unsupported versions, invalid core state shapes, unsafe object keys, cycles/non-JSON values and excessive state size are rejected before application state is changed. Application-specific metadata is preserved as JSON; these checks are not a substitute for validation/access control in a storage service.