---
title: React hooks
summary: The hooks and components in @spacemix/sdk/react - live collections and key/value, routes, notification targets, visibility, the environment, and widgets.
audience: both
stability: stable
since: protocol 1
---

# React hooks (`@spacemix/sdk/react`)

`@spacemix/sdk/react` (`packages/sdk/src/react.ts`) holds the hooks extension views use. They are thin layers over `host` (see [The host object](host/index.md)): everything they do, `host` can do outside React too. The frame provides the module at runtime (`HOST_MODULES` maps `@spacemix/sdk/react` to the global `__opSdkReact`), so the version your bundle runs against is the host's, not the one you built with. See [Contract](../contract.md).

```ts
import {
  useCollection, useStored, useRoute, useLinkTarget, useVisible, useEnv, useHost,
  useWidgetList, useWidgetFeed, WidgetFrame,
} from "@spacemix/sdk/react";
```

| Export | What for | Needs | Stability |
|---|---|---|---|
| [`useCollection`](#usecollection) | Live records of one of your collections, plus its API | the collection in the manifest | stable |
| [`useStored`](#usestored) | `useState` backed by `host.storage` | none | stable |
| [`useRoute`](#useroute) | The page inside the view, kept in the app's address | none | stable |
| [`useLinkTarget`](#uselinktarget) | The target of a notification the user opened | none | stable |
| [`useVisible`](#usevisible) | Whether the view is on screen | none | stable |
| [`useEnv`](#useenv) | The signed-in person and where the extension runs | none | stable |
| [`useHost`](#usehost) | The `host` object, as a hook | none | stable |
| [`useWidgetList`](#usewidgetlist) | The team's saved widgets, live | `widgets` or `widgets:view` | experimental |
| [`useWidgetFeed`](#usewidgetfeed) | One widget's status and data | `widgets` or `widgets:view` | experimental |
| [`WidgetFrame`](#widgetframe) | A widget, live, in a nested sandboxed frame | `widgets` or `widgets:view` | experimental |

## useCollection

```ts
function useCollection<T extends object>(name: string): { items: (T & RecordBase)[]; loaded: boolean } & CollectionApi<T>;
```

**Permission:** none checked at the bridge; the collection must be declared in your manifest.

**Behavior:** returns the records of your collection `name`, newest first (by `updatedAt`, then `createdAt`, the same order as `list()`), and the collection's API: `list`, `get`, `create`, `update`, `delete` (see [Collections](host/collections.md)). `items` updates live whenever anything changes the collection: this view, the assistant, an automation, another window or browser. A change pushed while the first read is in flight wins over that read. When `name` changes, the hook shows no items (`loaded: false`) until the new collection is read; it never shows one collection's records under another's name.

`loaded` is `false` until the first read finishes. Wait for it before treating something as missing.

**Errors:** if the first read fails, the error is logged to the console and the hook settles on `items: []`, `loaded: true`. Calling it with a name the manifest doesn't declare throws during render (`<id> declares no collection "<name>"`), which breaks the view; declare every collection you use.

**Example:**

```tsx
interface Note { title: string; body?: string }

function Notes() {
  const { items, loaded, create, delete: remove } = useCollection<Note>("notes");
  if (!loaded) return null;
  return (
    <ul>
      {items.map((n) => <li key={n.id} onClick={() => void remove(n.id)}>{n.title}</li>)}
      <li><button onClick={() => void create({ title: "Untitled" })}>New</button></li>
    </ul>
  );
}
```

**Stability:** stable.

## useStored

```ts
function useStored<T>(key: string, initial: T): readonly [T, (next: T | ((prev: T) => T)) => void, boolean];
```

**Permission:** none checked at the bridge.

**Behavior:** `useState` backed by `host.storage` under `key`, in your extension's own namespace (see [Storage](host/storage.md)). The value is shared with every other reader of the key: other components, other windows and browsers, and your actions. Returns `[value, set, loaded]`.

- `initial` is shown until the first read finishes and whenever nothing is stored (the stored value is `undefined`).
- The setter takes a value or an updater. An updater is resolved against the latest stored value anyone wrote or read, not against the last render, so two quick updates don't lose each other.
- Writes are applied to this frame's readers at once, then saved. The setter returns nothing; it doesn't wait for the save.
- `loaded` is `false` until the first read.

**Errors:** a failed read is logged and leaves `initial` with `loaded: true`. A failed write is logged to the console; the setter doesn't throw. A write the server refuses rolls the state back to the last saved value, or to `initial` when nothing was saved (see [Storage](host/storage.md#hoststorageset)).

**Limits:** the value must survive structured cloning and JSON (no functions, DOM nodes or class instances).

**Example:**

```tsx
const [settings, setSettings, loaded] = useStored("settings", { compact: false });
<input type="checkbox" checked={settings.compact} disabled={!loaded} onChange={() => setSettings((s) => ({ ...s, compact: !s.compact }))} />
```

Don't keep records in `useStored`; use a collection. Its writes go through `host.storage.set`, so a value over 64 KB is refused and logged to the console; the state keeps the value but nothing is saved (see [Storage](host/storage.md#hoststorageset)). See [Giving the assistant your data](../guide/giving-the-assistant-data.md).

**Stability:** stable.

## useRoute

```ts
function useRoute(): readonly [string, (route: string, options?: { replace?: boolean }) => void];
```

**Permission:** none.

**Behavior:** the view's current route (`host.view.route()`) and `host.view.navigate`. The route is a path you make up (`""` is the start page) that lives in the app's address after your extension's id: `#/@<server>/<extension id>/<route>`, where `@<server>` is the server's shortcode, the first 16 characters of its id, written by the host (see [Routes](host/view.md#routes)). The hook re-renders when the route changes, from `navigate` in this frame, Back and Forward, or a link.

- `navigate(route)` adds a history step. Nothing happens if `route` is the one already showing.
- `navigate(route, { replace: true })` rewrites the current step.

**Errors:** none thrown. If the host can't update the address, the error is logged; the route in this frame has already changed.

**Example:**

```tsx
const [route, navigate] = useRoute();
const [kind, id] = route.split("/");
return kind === "note" ? <NoteView id={id} onBack={() => navigate("")} /> : <NoteList onOpen={(n) => navigate(`note/${n}`)} />;
```

How to design routes: [Getting started](../guide/getting-started.md#pages-and-routes). The underlying API: [Routes](host/view.md#routes).

**Stability:** stable.

## useLinkTarget

```ts
function useLinkTarget(onTarget: (target: string) => void): void;
```

**Permission:** none.

**Behavior:** calls `onTarget` with the `target` of a notification the user opened (see `NotificationInput.target` in [Notifications](host/notifications.md)). It is delivered once, after the view is showing. A target that arrives while the view is hidden, or before anything listens, is held until both are true; only the latest held target is kept. The latest `onTarget` is always the one called, so you can pass an inline function.

**Example:**

```tsx
const [, navigate] = useRoute();
useLinkTarget((id) => navigate(`note/${id}`));
```

A target whose record no longer exists should leave the view as it is.

**Stability:** stable.

## useVisible

```ts
function useVisible(): boolean;
```

**Permission:** none.

**Behavior:** whether your view is on screen (the user has the extension open). Frames stay alive while hidden, so use it to pause timers, polling or animations. Same as `host.view.visible()` and `host.view.onVisible` (see [View](host/view.md)).

**Example:**

```tsx
const visible = useVisible();
useEffect(() => {
  if (!visible) return;
  const t = setInterval(refresh, 30_000);
  return () => clearInterval(t);
}, [visible]);
```

**Stability:** stable.

## useEnv

```ts
function useEnv(): SpacemixHost["env"]; // HostEnv
```

**Permission:** none.

**Behavior:** `host.env`: `desktop` (the desktop app rather than a browser), `platform` (`"macos"`, `"windows"`, `"linux"`, `"ios"`, `"android"` or `"web"`), `me` (`{ id, name, email }` of the signed-in person) and `serverName`. Fixed for the life of the frame, so it never re-renders. See [Environment and identity](host/env.md).

**Example:**

```tsx
const { me, desktop } = useEnv();
return <p>Signed in as {me.name}{desktop ? " on the desktop app" : ""}</p>;
```

**Stability:** stable.

## useHost

```ts
function useHost(): SpacemixHost;
```

**Permission:** none.

**Behavior:** returns `host`, the same object as `import { host } from "@spacemix/sdk"`. It is a hook only so it reads naturally in components; it never re-renders.

**Example:**

```tsx
const host = useHost();
<button onClick={() => void host.shell.copy(text)}>Copy</button>
```

**Stability:** stable.

## useWidgetList

```ts
function useWidgetList(): { widgets: Widget[]; ready: boolean };
```

**Permission:** `widgets` or `widgets:view`. Without either, it returns `{ widgets: [], ready: true }` and does nothing.

**Behavior:** the team's saved widgets, live. Widgets still unsaved in the Studio (`unsaved: true`) are left out. Re-reads on every change through `host.widgets.subscribe`; an older answer never replaces a newer one. `ready` is `false` until the first read. See [Widget reference](widgets.md).

**Errors:** a failed read is logged and sets `ready: true`, keeping the previous list.

**Example:**

```tsx
const { widgets, ready } = useWidgetList();
if (!ready) return null;
return <ul>{widgets.map((w) => <li key={w.id}>{w.name}</li>)}</ul>;
```

**Stability:** experimental: widgets in extensions are new and not yet exercised by third parties.

## useWidgetFeed

```ts
function useWidgetFeed(widgetId: string): { status: WidgetStatus; data?: WidgetData };
```

**Permission:** `widgets` or `widgets:view`.

**Behavior:** keeps the widget's sources running while the component is mounted (shared with every other place showing the same widget) and returns its live `status` and the sources' latest `data`, which comes out of the viewer's cache at once when that has something fresh (see `host.widgets.watch` and [The data cache](widgets.md#the-data-cache)). A status-only update keeps the data already shown; a purge (`host.widgets.purge`) drops it, so `data` is `undefined` again until the next fetch. Starts as `{ status: { state: "idle" } }`.

**Errors:** without a widget permission, `status` is `{ state: "error", error: "This extension can't show widgets." }`. A widget that doesn't exist reports `{ state: "error", error: "This widget no longer exists." }`.

**Example:**

```tsx
const { status, data } = useWidgetFeed(widget.id);
return (
  <div className="h-60">
    {status.state === "error" && <p className="text-danger">{status.error}</p>}
    <WidgetFrame widget={widget} data={data} status={status} />
  </div>
);
```

**Stability:** experimental (see `useWidgetList`).

## WidgetFrame

```ts
function WidgetFrame(props: { widget: Widget; data?: WidgetData; status?: WidgetStatus; className?: string }): ReactElement;
```

**Permission:** `widgets` or `widgets:view`.

**Behavior:** renders the widget, live, in a sandboxed iframe nested in your extension's frame (`sandbox="allow-scripts allow-forms"`, `referrerpolicy="no-referrer"`, its document from `host.widgets.frameUrl()`). It speaks the widget frame protocol for you: it posts `render` once the frame is loaded and data is in, then `data` on every update and `theme` when the app's theme changes; it answers the widget's `call` with `host.widgets.call`, opens an extension on `open` with `host.shell.open`, and reports script errors with `host.widgets.reportError`. See [Widget reference](widgets.md#the-widget-frame).

- Pass `data` (from `useWidgetFeed`) when you show the status yourself; `undefined` means still loading. Leave the prop out entirely and the frame watches the widget on its own.
- Pass `status` with `data` and the frame shows an "Extension uninstalled" pill in place of the widget when `status.missing` is set; clicking it lists which extensions. Without `data` it watches the status itself.
- It fills its container (`height: 100%`), so give the container a height. It uses inline styles only and shows a pulsing skeleton until the first render.
- A change to the widget's `html` creates a fresh frame document, so the old code's globals and timers don't carry over. So does `data` going back to `undefined` after a purge: the skeleton shows until the new data is in.

**Errors:** if the frame document's URL can't be read, the error is reported as the widget's script error.

**Example:**

```tsx
<div className="h-48 rounded-lg border border-border">
  <WidgetFrame widget={widget} />
</div>
```

**Stability:** experimental (see `useWidgetList`).
