Skip to Content
OrbixDocs
Block SDK · Guides

Store and sync state

Persist block data, separate team and personal scopes, collect per-member input, and choose the right storage layer.

Orbix provides several hooks for storing data inside a block. Which hook you choose depends on whether the data belongs to the document (shared with everyone viewing the page), to the current viewer, or only to the current browser device.

Choosing the right hook

HookWhere data livesSynced with document?Works in read-only?Capability required
useOrbixState (scope: 'team')Block props on the pageYesNo (writes dropped)None
useOrbixState (scope: 'personal') / usePersonalStateViewer-scoped statePer userYesNone
useMemberState / useVotingPer-member slots on the blockYesNoNone
useStorageBrowser localStorage (by default)No (device-local)Memory-only fallbackstorage: ['local'] (community default)
usePersistentStorageBrowser IndexedDBNo (device-local)Nostorage: ['local', 'persistent']
useSessionStorageBrowser sessionStorageNo (tab-local)Yesstorage: ['local', 'session']
useCacheIn-memory TTL mapNoYesstorage: ['local', 'cache'] (community default)

useOrbixState

useOrbixState is the primary state hook for blocks. It returns a three-item tuple [state, setState, controls]:

  • setState has a stable function identity across renders and accepts a replacement value, a shallow Partial<T> (for whole-object state), or a functional updater (prev) => next.
  • Multiple keyed setState calls in the same tick are coalesced into a single animation-frame patch so sibling keys do not overwrite one another.
  • Structurally equal updates are skipped without triggering a host write.

Whole-object vs keyed state

Pass props and a default object to manage the block's state as one record, or pass a string key to manage independent fields:

src/index.tsx
import { defineBlock, useOrbixState, type BlockRenderProps } from '@orbixdocs/sdk';

interface TimerState {
  minutes: number;
  running: boolean;
}

export default defineBlock({
  manifest: {
    id: 'acme.focus-box',
    name: 'Focus Box',
    version: '1.0.0',
    sdk: '^3.0.0',
  },
  component(props: BlockRenderProps) {
    // 1. Shared team state stored on the block
    const [timer, setTimer, controls] = useOrbixState<TimerState>(props, {
      minutes: 25,
      running: false,
    });

    // 2. Keyed personal state (isolated per viewer, editable even in read-only mode)
    const [activeTab, setActiveTab] = useOrbixState<'timer' | 'notes'>(
      props,
      'activeTab',
      'timer',
      { scope: 'personal' }
    );

    return (
      <div
        style={{
          padding: 16,
          borderRadius: 12,
          background: 'var(--orbix-card-bg, #16171b)',
          border: '1px solid var(--orbix-surface-border, #2a2b32)',
          color: 'var(--orbix-text-primary, #f4f4f5)',
        }}
      >
        <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
          <button type="button" onClick={() => setActiveTab('timer')}>
            Timer ({activeTab === 'timer' ? 'active' : 'inactive'})
          </button>
          <button type="button" onClick={() => setActiveTab('notes')}>
            Notes
          </button>
        </div>

        {activeTab === 'timer' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>{timer.minutes} min</span>
            <button
              type="button"
              disabled={props.isReadOnly}
              onClick={() => setTimer((prev) => ({ ...prev, minutes: prev.minutes + 5 }))}
            >
              +5m
            </button>
            <button
              type="button"
              disabled={props.isReadOnly || !controls.canUndo}
              onClick={controls.undo}
            >
              Undo
            </button>
          </div>
        )}
      </div>
    );
  },
});

Supported scope values

StateOptions.scope resolves in this order: explicit options.scope -> enclosing <PersonalScope> or <TeamScope> wrapper -> block.props.blockScopeMode -> 'team'.

  • 'team' (also 'global' or 'shared') — shared across everyone viewing the block. Blocked with a console warning when isReadOnly is true.
  • 'personal' (also 'local' or 'session') — private to the current user. Continues to work when isReadOnly is true.

Do not pass scope: 'member' to useOrbixState

Although 'member' appears in the OrbixDataScope union type, useOrbixState only branches on 'personal' vs 'team' and falls back to 'team'. To store one value per workspace member without overwrites, use useMemberState or useVoting below.

Undo, redo, and reset

The third tuple element controls provides local history for that state hook (up to historyLimit, default 50):

  • controls.undo() and controls.redo()
  • controls.canUndo and controls.canRedo
  • controls.reset() — restores the initial default value

Per-member state and voting

When several people interact with the same block (such as an estimation card, standup check-in, or poll), each member needs their own slot rather than overwriting a shared key.

src/PollCard.tsx
import { useMemberState, useVoting } from '@orbixdocs/sdk';

export function EstimationAndPoll() {
  const estimate = useMemberState<number | null>('storyPoints', null);
  const poll = useVoting('release_gate', {
    question: 'Ready to ship v1.2?',
    options: ['Ship today', 'Hold for QA'],
  });

  return (
    <div>
      <div>
        <span>Your estimate: {estimate.myValue ?? 'Not set'}</span>
        <span> ({estimate.count} submitted)</span>
        <button type="button" onClick={() => estimate.setMyValue(5)}>
          Vote 5 pts
        </button>
      </div>

      <h4>{poll.question}</h4>
      {poll.results.map((opt) => (
        <button key={opt.id} type="button" onClick={() => poll.vote(opt.id)}>
          {opt.label}: {opt.count} ({opt.percentage}%)
        </button>
      ))}
    </div>
  );
}

When you pass plain strings to useVoting(..., { options: ['Yes', 'No'] }), the SDK assigns deterministic IDs 'opt_1', 'opt_2', and so on. Pass { id, label, description? } objects if you want stable custom option IDs across edits.

Device storage (useStorage and usePersistentStorage)

Use device storage hooks for data that should stay on the current browser (draft inputs, cached payloads, or large blobs) rather than syncing into the document's block properties:

src/DraftBox.tsx
import { useStorage, usePersistentStorage } from '@orbixdocs/sdk';

export function DraftBox() {
  // Defaults to device localStorage ('local' capability is included in community defaults)
  const [draft, setDraft, meta] = useStorage<string>('scratch_draft', '');

  // Uses IndexedDB; requires capabilities: { storage: ['local', 'persistent'] }
  const [archive, setArchive, archiveLoading] = usePersistentStorage<string[]>(
    'saved_notes',
    []
  );

  if (meta.loading || archiveLoading) {
    return <div>Loading local data...</div>;
  }

  return (
    <div>
      <textarea
        value={draft}
        onChange={(e) => {
          void setDraft(e.target.value);
        }}
      />
      <button
        type="button"
        onClick={() => {
          void setArchive([...archive, draft]);
          void setDraft('');
        }}
      >
        Save to local archive ({archive.length})
      </button>
    </div>
  );
}

Note two details when using useStorage and usePersistentStorage:

  1. Their setter functions are asynchronous (Promise<void>), and initial hydration sets loading: true until the stored value resolves. Calling set before hydration completes cancels the stale initial read so your new value is not overwritten.
  2. Community blocks receive storage: ['local', 'cache'] by default. If you add persistent or session in manifest.capabilities.storage, include 'local' in the array too (storage: ['local', 'persistent']) because declaring a capability key replaces its tier default.

On this page