Hooks and composables
The React and Vue adapters expose the same four subscriptions for UI around a spreadsheet:
| Need | React | Vue |
|---|---|---|
| Show the active cell or range | useSelection(spreadsheet) | useSelection(spreadsheetRef) |
| Derive a value for a host panel | useSpreadsheet(spreadsheet, selector) | useSpreadsheet(spreadsheetRef, selector) |
| Follow the active locale and labels | useI18n(spreadsheet) | useI18n(spreadsheetRef) |
| React to a named spreadsheet event | useSpreadsheetEvent(spreadsheet, event, handler) | useSpreadsheetEvent(spreadsheetRef, event, handler) |
These hooks subscribe to the instance that the adapter mounted. Pass null in React while the spreadsheet is mounting; in Vue, pass a ref, a getter, or a plain value of SpreadsheetInstance | null. React hooks return null until an instance is ready, Vue composables return a shallow ref holding null, and both switch subscriptions when the instance changes or is disposed.
The hooks observe state and events. They do not own the spreadsheet or call dispose(). The <Spreadsheet> adapter disposes its instance when its component leaves the tree. A host that calls mount() owns that instance and must dispose it at the end of the host view.
Host updates and events
Apply a trusted host snapshot and inspect selection and change events from the live instance.
Powered by the real Formulon engine (WASM) — it runs entirely in your browser, nothing is uploaded.
React: selection inspector and edit status
This example puts a spreadsheet and a host-owned inspector in the same component. It combines all four hooks:
useSelectionsupplies the active cell and the selected ranges.useSpreadsheetderives the name of the active sheet.useI18nsupplies the locale and the status-bar label for the inspector.useSpreadsheetEventupdates the inspector after an appliedchange.
import { useState } from 'react'
import { formatA1Cell, type SpreadsheetInstance, type SpreadsheetUiOptions } from '@libraz/formulon-cell'
import {
Spreadsheet,
useI18n,
useSelection,
useSpreadsheet,
useSpreadsheetEvent,
} from '@libraz/formulon-cell-react'
import '@libraz/formulon-cell/styles.css'
// A module constant keeps the prop stable while the inspector re-renders.
const ui: SpreadsheetUiOptions = { profile: 'embedded', features: { shortcuts: true, clipboard: true } }
export function SheetWithInspector() {
const [spreadsheet, setSpreadsheet] = useState<SpreadsheetInstance | null>(null)
const [lastEdit, setLastEdit] = useState<string | null>(null)
const [mountError, setMountError] = useState<string | null>(null)
// Hooks stay above the render branches. They also work while spreadsheet is null.
const selection = useSelection(spreadsheet)
const sheetName = useSpreadsheet(spreadsheet, (s) =>
s.workbook.sheet(s.selection.get().sheet).name,
)
const i18n = useI18n(spreadsheet)
useSpreadsheetEvent(spreadsheet, 'change', (event) => {
if (event.status !== 'applied') return
const label = i18n?.strings.statusBar.cells ?? 'cells'
setLastEdit(`${event.applied.length} ${label} (${event.origin})`)
})
const cellCount = (selection?.ranges ?? []).reduce(
(sum, r) => sum + (r.lastRow - r.firstRow + 1) * (r.lastCol - r.firstCol + 1),
0,
)
return (
<section className="sheet-layout">
<div className="sheet-host">
<Spreadsheet
ui={ui}
locale="en"
onReady={setSpreadsheet}
onError={(error) => setMountError(error instanceof Error ? error.message : String(error))}
style={{ width: '100%', height: 420 }}
/>
</div>
<aside className="sheet-inspector" aria-live="polite">
{spreadsheet && selection && i18n ? (
<>
<strong>{i18n.strings.statusBar.ready}</strong>
<label>
Language
<select
value={i18n.locale}
onChange={(event) => {
try {
spreadsheet.update({ locale: event.target.value })
} catch {
// The spreadsheet kept its language; the select re-renders from i18n.locale.
}
}}
>
<option value="en">English</option>
<option value="ja">日本語</option>
</select>
</label>
<span>Active cell: {sheetName}!{formatA1Cell(selection.active.row, selection.active.col)}</span>
<span>Selected: {cellCount} cells</span>
<span>{lastEdit ?? 'No applied edit yet'}</span>
</>
) : !mountError ? (
<span>Loading spreadsheet…</span>
) : null}
{mountError && <span role="alert">{mountError}</span>}
</aside>
</section>
)
}Give the spreadsheet host a real height. The imported core stylesheet supplies the grid styles; the host layout supplies the space in which the adapter can render it.
.sheet-layout {
display: grid;
gap: 12px;
min-width: 0;
}
.sheet-host {
min-height: 320px;
height: 420px;
}
.sheet-inspector {
display: flex;
gap: 12px;
flex-wrap: wrap;
}The hook calls remain unconditional even before onReady fires. Keep the spreadsheet component mounted while the inspector changes; conditionally render the inspector contents instead of replacing the <Spreadsheet> element after the instance becomes ready.
The count above sums every rectangle in selection.ranges, so a disjoint selection (users add an area by holding Ctrl or Cmd while dragging) is counted in full. selection.range is the rectangle the active cell is in.
Vue: the same inspector as an SFC
Vue composables receive the ref itself. Pass spreadsheet to every composable, never spreadsheet.value; the composable watches the ref and replaces its subscription when the adapter becomes ready or a new instance is installed. Each composable returns a shallow ref.
<script setup lang="ts">
import { computed, ref, shallowRef } from 'vue'
import { formatA1Cell, type SpreadsheetInstance, type SpreadsheetUiOptions } from '@libraz/formulon-cell'
import {
Spreadsheet,
useI18n,
useSelection,
useSpreadsheet,
useSpreadsheetEvent,
} from '@libraz/formulon-cell-vue'
import '@libraz/formulon-cell/styles.css'
const ui: SpreadsheetUiOptions = { profile: 'embedded', features: { shortcuts: true, clipboard: true } }
const spreadsheet = shallowRef<SpreadsheetInstance | null>(null)
const lastEdit = ref<string | null>(null)
const mountError = ref<string | null>(null)
const selection = useSelection(spreadsheet)
const sheetName = useSpreadsheet(spreadsheet, (s) => s.workbook.sheet(s.selection.get().sheet).name)
const i18n = useI18n(spreadsheet)
useSpreadsheetEvent(spreadsheet, 'change', (event) => {
if (event.status !== 'applied') return
const label = i18n.value?.strings.statusBar.cells ?? 'cells'
lastEdit.value = `${event.applied.length} ${label} (${event.origin})`
})
const activeCell = computed(() =>
selection.value
? `${sheetName.value}!${formatA1Cell(selection.value.active.row, selection.value.active.col)}`
: '',
)
const cellCount = computed(() =>
(selection.value?.ranges ?? []).reduce(
(sum, r) => sum + (r.lastRow - r.firstRow + 1) * (r.lastCol - r.firstCol + 1),
0,
),
)
const onError = (error: unknown) => {
mountError.value = error instanceof Error ? error.message : String(error)
}
const changeLocale = (event: Event) => {
try {
spreadsheet.value?.update({ locale: (event.target as HTMLSelectElement).value })
} catch {
// The spreadsheet kept its language.
}
}
</script>
<template>
<section class="sheet-layout">
<div class="sheet-host">
<Spreadsheet
:ui="ui"
locale="en"
style="width: 100%; height: 420px"
@ready="spreadsheet = $event"
@error="onError"
/>
</div>
<aside class="sheet-inspector" aria-live="polite">
<template v-if="spreadsheet && i18n">
<strong>{{ i18n.strings.statusBar.ready }}</strong>
<label>
Language
<select :value="i18n.locale" @change="changeLocale">
<option value="en">English</option>
<option value="ja">日本語</option>
</select>
</label>
<span>Active cell: {{ activeCell }}</span>
<span>Selected: {{ cellCount }} cells</span>
<span>{{ lastEdit ?? 'No applied edit yet' }}</span>
</template>
<span v-else-if="!mountError">Loading spreadsheet…</span>
<span v-if="mountError" role="alert">{{ mountError }}</span>
</aside>
</section>
</template>
<style scoped>
.sheet-layout {
display: grid;
gap: 12px;
min-width: 0;
}
.sheet-host {
min-height: 320px;
height: 420px;
}
.sheet-inspector {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
</style>Vue templates use kebab-case for component events such as @selection-change and @locale-change. The event names passed to useSpreadsheetEvent are the instance event names: change, cell, workbook, recalc, update, and error. Their payloads: change is a ChangeBatchResult plus origin; cell is { sheet, at, value, origin } and carries no formula; workbook is { workbook }; recalc is { cells }; update is { keys, source }; error is { error, source }. selection.on('change'), useSelection, and the selectionChange event give a SelectionState: { sheet, active, range, ranges }.
Use case: show refused changes
useSpreadsheetEvent(spreadsheet, 'change', handler) follows applied batches. A change the policy or sheet protection refuses is not an applied batch. For an edit the user makes in the grid, the spreadsheet shows the refusal itself, with the reason in the UI language. For a write the host issues, applyChanges() returns the ChangeBatchResult: status is 'refused', nothing was written, and rejections holds the refusal that decided it.
React can show that result next to the host control that issued it, and ask commands.can() first to disable the control when the write would be refused:
import { useState } from 'react'
import type { SpreadsheetInstance } from '@libraz/formulon-cell'
import { useSelection } from '@libraz/formulon-cell-react'
export function ApproveButton({ spreadsheet }: { spreadsheet: SpreadsheetInstance | null }) {
const [message, setMessage] = useState<string | null>(null)
// Re-render on selection changes so the permission check below stays current.
useSelection(spreadsheet)
const allowed =
spreadsheet?.commands.can({ kind: 'edit', operation: 'valueEdit', at: 'E2' }) ?? false
const approve = () => {
if (!spreadsheet) return
const result = spreadsheet.applyChanges([{ at: 'E2', input: 'Approved' }], { history: 'record' })
const first = result.rejections[0]
setMessage(result.status === 'refused' ? `${first?.code}: ${first?.reason}` : null)
}
return (
<>
<button disabled={!allowed} onClick={approve}>Approve</button>
{message && <p role="alert">{message}</p>}
</>
)
}commands.can() follows the policy, the protection, and the selection, so ask again after an update, a change, or a selection change. The reason of a refusal is English text paired with its code. A built-in refusal also carries reasonKey, a stable key a host can translate the reason by; a reason the host supplied has none. The spreadsheet's own UI shows the localized reason.
Use case: localized host controls
Use useI18n when a host-owned panel should follow the UI language or label overrides. The returned strings are the same dictionary the spreadsheet UI uses, so a host control can share the active locale without maintaining a second locale subscription. update({ locale }) throws and keeps the current locale when the change is rejected; Language switching shows the complete flow.
const i18n = useI18n(spreadsheet)
return (
<label>
{i18n?.locale === 'ja' ? '言語' : 'Language'}
<select
disabled={!spreadsheet}
value={i18n?.locale ?? 'en'}
onChange={(event) => {
try {
spreadsheet?.update({ locale: event.target.value })
} catch {
showLanguageError()
}
}}
>
<option value="en">English</option>
<option value="ja">日本語</option>
</select>
<span>{i18n?.strings.statusBar.ready}</span>
</label>
)The result is null in React, and the Vue ref holds null, until the instance is ready; guard nested labels in a template or computed value, and disable a locale-bound control until then, as above.
Use case: derive a host view from spreadsheet state
Use useSpreadsheet when the panel needs a small derived value rather than the whole instance. The selector receives the instance and runs again after every applied change, cell change, workbook swap, recalculation, option update, selection change, and locale change. The result is null while no instance is available.
const activeSheet = useSpreadsheet(spreadsheet, (s) => s.selection.get().sheet)
const zoom = useSpreadsheet(spreadsheet, (s) => s.viewport.zoomPercent)
const canUndo = useSpreadsheet(spreadsheet, (s) => s.history.canUndo)Select only what the panel renders. Keep workbook operations on SpreadsheetInstance; use the hook for a reactive display value.
Which subscription should own the work?
Use the narrowest boundary that matches the task:
- Use
useSelection,useSpreadsheet, oruseI18nwhen a host component must re-render from current spreadsheet state. - Use
useSpreadsheetEventfor a named event that triggers a side effect in the component, such as an applied edit counter or a recalculation notice. - Use
onReady,onError, and the adapter's event props for a small mount-boundary callback. In Vue templates, use the adapter's kebab-case event spelling. - Use
instance.on(event, listener),instance.selection.on('change', listener), orinstance.i18n.on('change', listener)for a service or host controller that lives outside a React or Vue component. Keep the returned disposer and call it when that service stops.
Do not wire the same event through both a hook and an adapter prop unless two independent consumers need it. Hooks clean up their own subscriptions when the component scope ends or when the instance changes. They never replace the owner-side instance.dispose() call.
Outside a component, call the disposer when the observer stops:
const offSelection = instance.selection.on('change', (state) => {
console.log('selection changed', state.range)
})
function stopWatching() {
offSelection()
}If a view replaces its spreadsheet instance, update the owner-side instance reference at the same time. React hooks resubscribe on the new object; Vue composables watch the ref and dispose the old subscription before attaching the new one.
The observer owns its subscription. The mount owner disposes the instance and manages any caller-supplied workbook separately. See embedding and cleanup.
Related: React and Vue setup, host integration, and localization.