# State persistence

> Save and restore the user's grid state with persistState, read and apply it with getState and restoreState, reset it, share it as a URL-safe string, and keep named saved views.

Canonical: https://salmonui.dev/docs/data-grid/state-persistence

`persistState` saves what the user did to the grid and restores it the next
time the grid mounts:

```tsx
<DataGrid id="orders" persistState data={orders} columns={columns} sorting filtering paging />
```

With `true` the state goes to `localStorage` under the key
`salmon-data-grid:<id>`, so the grid needs a stable `id` (without one a
development warning explains that nothing is persisted). Saves are
coalesced: a burst of changes writes once.

## What is persisted

The state (`DataGridState`) has one part per feature (`DataGridStatePart`):

| Part | Contents |
| --- | --- |
| `columns` | Column order, widths and visibility |
| `pinning` | Columns pinned at runtime |
| `sorting` | Sorted columns and directions |
| `filters` | Filter conditions per column |
| `grouping` | Grouped columns |
| `paging` | Page and page size |
| `search` | Search text and options |
| `pinnedRows` | Rows pinned at runtime |
| `tree` | Tree mode expansion |
| `selection` | Selected rows |
| `scroll` | Scroll position |

Columns are referenced by field or column id; a stored column that no longer
exists is dropped and reported instead of failing the restore. Templates and
other definition-time settings are never stored: they come from the props.

## Options

An object configures the binding:

```tsx
<DataGrid
  id="orders"
  persistState={{
    key: 'orders-view',            // default `salmon-data-grid:<id>`
    storage: myStorage,            // default localStorage
    exclude: ['selection', 'scroll'],
    version: 3,
    migrate: (state, version) => (version === 2 ? upgrade(state) : null),
  }}
/>
```

- `storage` is any object with `load(key)`, `save(key, state)` and an
  optional `remove(key)`; each may be synchronous or return a promise, so
  `sessionStorage`, IndexedDB or a server endpoint fit. `@salmonui/data`
  `createKeyValueStateStorage` and `createJsonStateStorage` build such
  storages over a key-value store or the JSON protocol endpoint.
- `exclude` leaves parts out of saving and restoring.
- `version` is the application state version. A state saved by
  another version is discarded, unless `migrate` upgrades it; returning
  `null` from `migrate` discards it too. The state itself also carries a
  schema version, so a state from an older Salmon UI release is upgraded or
  rejected rather than half applied.

## SSR and hydration

Storage is read only in the browser, after mount. The server and the
hydrating client both render the definition state, so there is no hydration
mismatch; the stored state is restored right after hydration, in the same
task, before the browser paints.

## The state API

The same state is available through the grid instance (`ref` or
`useDataGridApi()`):

- `api.getState(options?)` returns the current `DataGridState`, a plain JSON
  object; `{ exclude }` leaves parts out.
- `api.restoreState(stateOrString, options?)` applies a state in one batch
  without recompiling columns. It returns
  `{ status: 'applied' | 'partial', ignoredColumns, rejected, skipped, scroll }`:
  `partial` lists columns that no longer exist, commands the grid rejected,
  and parts whose feature is not enabled.
- `api.resetState()` returns to the definition state (the props the grid was
  created with) and, when `persistState` is on, clears the stored entry.

`serializeDataGridState(state)` and `deserializeDataGridState(text)` from
`@salmonui/data-grid` convert a state to and from a compact, URL-safe
base64url string, for example to share a view in a link:

```ts
const url = `${location.pathname}?view=${serializeDataGridState(api.getState({ exclude: ['selection', 'scroll'] }))}`;
// Later: api.restoreState(new URLSearchParams(location.search).get('view') ?? '');
```

`restoreState` accepts the serialized string directly.

## Named saved views

Named views sit on top of the same state API: `createSavedViews` from `@salmonui/data/views`
keeps a list of named `DataGridState` values for one grid in any key-value store
(`localStorage`, `sessionStorage`, an IndexedDB wrapper, a server-backed
store). The grid never imports it, so it adds nothing to a grid that does
not use it.

```tsx
import { createSavedViews } from '@salmonui/data/views';

// In an effect or event handler (localStorage does not exist on the server):
const views = createSavedViews(localStorage, { gridId: 'orders' });

// Save the current layout under a name (an existing `id` replaces that view).
await views.save({ name: 'Open orders', state: api.getState({ exclude: ['selection', 'scroll'] }) });

// List, apply, rename and delete.
const list = await views.list();          // [{ id, name, description?, state, createdAt, updatedAt, schemaVersion }]
api.restoreState(list[0].state);
await views.rename(list[0].id, 'Unshipped');
await views.remove(list[0].id);
```

- A view is `{ id, name, description?, state, createdAt, updatedAt,
  schemaVersion }`. All views of a grid are stored as one JSON document under
  `salmonui:grid-views:<gridId>` (`prefix` changes the key).
- `subscribe(listener)` reports the list after every change, so a view
  picker stays in sync; writes are queued, so two quick saves never drop
  each other.
- `migrate(record, schemaVersion)` upgrades records written by an older
  format or drops them by returning `null`. The grid state inside a view
  keeps its own schema version, which `restoreState` checks as usual.
- Applying a view is an ordinary `restoreState`: one batch, no column
  recompile, and the same `RestoreResult`. Combine it with `persistState`
  to also remember the last layout the user had.

### Live demo: Named saved views

Live demo: https://salmonui.dev/demos/data-grid/saved-views

Save the current sort, filters, grouping, page and column layout under a name, switch between saved views, and delete them; views are stored in localStorage with createSavedViews and applied with restoreState.

`Demo.tsx`:

```tsx
'use client';

import { useEffect, useRef, useState } from 'react';
import { createMemoryStore, type KeyValueStore } from '@salmonui/data';
import { createSavedViews, type SavedView, type SavedViews } from '@salmonui/data/views';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridState } from '@salmonui/data-grid';
import { TextField } from '@salmonui/inputs/text-field';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(1_000, 23);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

/** localStorage when the browser allows it, else memory. Called in an effect only (never on the server). */
function browserStore(): KeyValueStore {
  try {
    const storage = globalThis.localStorage;
    if (storage) return storage;
  } catch {
    // Private mode or blocked storage.
  }
  return createMemoryStore();
}

export default function SavedViewsDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [views, setViews] = useState<SavedViews<DataGridState> | null>(null);
  const [list, setList] = useState<readonly SavedView<DataGridState>[]>([]);
  const [name, setName] = useState('My view');
  const [status, setStatus] = useState('Sort, filter, group or resize, then save the layout as a named view.');

  useEffect(() => {
    const store = createSavedViews<DataGridState>(browserStore(), { gridId: 'docs-saved-views' });
    setViews(store);
    const off = store.subscribe(setList);
    void store.list().then(setList);
    return off;
  }, []);

  return (
    <>
      <div className="demo-toolbar">
        <label>
          View name{' '}
          <TextField value={name} onValueChange={setName} aria-label="View name" />
        </label>
        <Button
          variant="outline"
          disabled={!views || name.trim() === ''}
          onClick={async () => {
            const state = api.current?.getState({ exclude: ['selection', 'scroll'] });
            if (!views || !state) return;
            const existing = list.find((v) => v.name === name.trim());
            const view = await views.save({ ...(existing ? { id: existing.id } : {}), name: name.trim(), state });
            setStatus(`${existing ? 'Updated' : 'Saved'} view "${view.name}".`);
          }}
        >
          Save view
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            if (!api.current) return;
            api.current.resetState();
            setStatus('Back to the default layout.');
          }}
        >
          Default layout
        </Button>
      </div>
      <div className="demo-toolbar" role="group" aria-label="Saved views">
        {list.length === 0 ? <span>No saved views yet.</span> : null}
        {list.map((view) => (
          <span key={view.id}>
            <Button
              variant="outline"
              onClick={() => {
                const result = api.current?.restoreState(view.state);
                if (result) setStatus(`Applied "${view.name}": ${result.status}.`);
              }}
            >
              {view.name}
            </Button>{' '}
            <Button
              variant="outline"
              aria-label={`Delete view ${view.name}`}
              onClick={async () => {
                await views?.remove(view.id);
                setStatus(`Deleted "${view.name}".`);
              }}
            >
              Delete
            </Button>
          </span>
        ))}
      </div>
      <DataGrid<Order>
        id="docs-saved-views"
        aria-label="Orders with named saved views"
        data={orders}
        columns={columns}
        sorting={{ multiple: true }}
        filtering
        grouping
        paging={{ pageSize: 10 }}
        resizable
        reorderable
        height={360}
        locale="en-US"
        currency="USD"
        ref={api}
      />
      <p className="demo-status" aria-live="polite">
        {status}
      </p>
    </>
  );
}
```

## Restoring keeps the compiled columns

`restoreState` and `resetState` apply column order, widths, visibility and
pinning as runtime commands on the existing columns; the column definitions
are never recompiled, so templates, formatters and lookups stay in place and
the restore costs one notification. The demo below checks it:
`api.getColumn(field)` returns the same compiled column before and after a
restore.

## Controlled state

State persistence is optional. An application that owns the view (in a URL,
a store or a server) can control it entirely through props, the additive
counterpart of `getState()` / `restoreState()`:

| State | Prop | Change event |
| --- | --- | --- |
| Sort | `sorting.sortBy` | `onSortChange` |
| Filters | `filtering.filters` | `onFilterChange` |
| Search | `search.text` | `onSearchChange` |
| Page | `paging.page`, `paging.pageSize` | `onPageChange` |
| Grouping | `grouping.groupBy` | `onGroupChange` |
| Column visibility, width, pinning, order | column `hidden`, `width`, `pinned`, array order | `onColumnVisibilityChange`, `onColumnResizeEnd`, `onColumnPinChange`, `onColumnReorder` |
| Selection | `selection.rowIds` | `onSelectionChange` |

Options props are compared structurally with their previous value, so an
object recreated with the same content is a no-op, and a changed value is
applied as a command (not a remount). Writing the event payload back into
your state closes the loop. Every change event carries `source`
(`'pointer'`, `'keyboard'`, `'touch'` or `'api'`), and `restoreState` raises the same
events, so a restored snapshot reaches the application state too. Keep
scroll positions, hover and drag state out of React state: the grid owns
those transients.

### Live demo: Controlled grid state

Live demo: https://salmonui.dev/demos/data-grid/controlled-state

The application owns the sort, filters, search, page, hidden columns and selection through reactive props and change events, takes a getState() snapshot and restores it without recompiling columns.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridFilter, type DataGridSortItem, type DataGridState } from '@salmonui/data-grid';
import { TextField } from '@salmonui/inputs/text-field';
import type { RowId } from '@salmonui/core/data';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(500, 23);

const baseColumns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

/** The whole view, owned by the application. */
interface View {
  readonly sortBy: readonly DataGridSortItem[];
  readonly filters: readonly DataGridFilter[];
  readonly search: string;
  readonly page: number;
  readonly hidden: readonly string[];
  readonly selected: readonly RowId[];
}

const initialView: View = { sortBy: [{ field: 'amount', direction: 'desc' }], filters: [], search: '', page: 1, hidden: [], selected: [] };

export default function ControlledStateDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [view, setView] = useState<View>(initialView);
  const [snapshot, setSnapshot] = useState<DataGridState | null>(null);
  const [status, setStatus] = useState('Sort, filter, search, page, hide or select in the grid, or use the buttons: both sides stay in sync.');
  const patch = (next: Partial<View>) => setView((current) => ({ ...current, ...next }));

  // Reactive props: each re-applies when its value changes (compared structurally),
  // and each matching event writes the grid's change back into `view`.
  const columns = useMemo(() => baseColumns.map((c) => ({ ...c, hidden: view.hidden.includes(c.field ?? '') })), [view.hidden]);
  const sorting = useMemo(() => ({ sortBy: view.sortBy }), [view.sortBy]);
  const filtering = useMemo(() => ({ filters: view.filters }), [view.filters]);
  const search = useMemo(() => ({ text: view.search }), [view.search]);
  const paging = useMemo(() => ({ page: view.page, pageSize: 10 }), [view.page]);
  const selection = useMemo(() => ({ multiple: true, rowIds: view.selected }), [view.selected]);

  return (
    <>
      <div className="demo-toolbar">
        <TextField type="search" aria-label="Search orders" placeholder="Search" value={view.search} onValueChange={(value) => patch({ search: value, page: 1 })} />
        <Button variant="outline" onClick={() => patch({ sortBy: [{ field: 'customer', direction: 'asc' }], page: 1 })}>
          Sort by customer
        </Button>
        <Button variant="outline" onClick={() => patch({ filters: [{ field: 'country', operator: 'equal', value: 'Japan' }], page: 1 })}>
          Only Japan
        </Button>
        <Button variant="outline" onClick={() => patch({ page: 3 })}>
          Page 3
        </Button>
        <Button variant="outline" onClick={() => patch({ hidden: view.hidden.includes('product') ? [] : ['product'] })}>
          Toggle Product
        </Button>
        <Button variant="outline" onClick={() => setView(initialView)}>
          Reset view
        </Button>
      </div>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            const state = api.current?.getState({ exclude: ['scroll'] });
            if (!state) return;
            setSnapshot(state);
            setStatus('Snapshot taken with getState().');
          }}
        >
          Take snapshot
        </Button>
        <Button
          variant="outline"
          disabled={snapshot === null}
          onClick={() => {
            const grid = api.current;
            if (!grid || !snapshot) return;
            // Compiled columns are immutable: the same object after the restore means no recompile.
            const before = grid.getColumn('customer');
            const result = grid.restoreState(snapshot);
            const recompiled = grid.getColumn('customer') !== before;
            setStatus(`restoreState: ${result.status}; columns recompiled: ${recompiled ? 'yes' : 'no'}.`);
          }}
        >
          Restore snapshot
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with application-owned view state"
        ref={api}
        data={orders}
        columns={columns}
        sorting={sorting}
        filtering={filtering}
        search={search}
        paging={paging}
        selection={selection}
        height={300}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        onSortChange={(event) => patch({ sortBy: event.sortBy })}
        onFilterChange={(event) => patch({ filters: event.filters })}
        onSearchChange={(event) => patch({ search: event.text })}
        onPageChange={(event) => patch({ page: event.page })}
        onColumnVisibilityChange={(event) => setView((current) => ({ ...current, hidden: [...current.hidden.filter((f) => !event.shown.includes(f)), ...event.hidden] }))}
        onSelectionChange={(event) => patch({ selected: event.rowIds })}
      />
      <p className="demo-status" aria-live="polite">
        {status}
      </p>
      <pre className="demo-log" aria-label="Application view state" tabIndex={0}>
        {JSON.stringify(view, null, 2)}
      </pre>
    </>
  );
}
```

### Live demo: State persistence

Live demo: https://salmonui.dev/demos/data-grid/state-persistence

A grid with an id and persistState saves sorting, filters, paging, column order and widths to localStorage and restores them after a reload; buttons read, restore, reset and serialize the state.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, serializeDataGridState, type DataGridApi, type DataGridColumn, type DataGridPersistState, type DataGridRestoreResult, type DataGridState } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(1_000, 17);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMd', width: 130 },
];

// Saved to localStorage under `salmon-data-grid:docs-orders-state` after every change and
// restored after mount. Bump `version` when a release changes the columns:
// states saved by another version are discarded. Constant: the prop is read on mount.
const persistState: DataGridPersistState = { version: 1 };

function describe(result: DataGridRestoreResult): string {
  const notes = [
    result.ignoredColumns.length ? `ignored columns: ${result.ignoredColumns.join(', ')}` : '',
    result.skipped.length ? `skipped parts: ${result.skipped.join(', ')}` : '',
    result.rejected.length ? `rejected: ${result.rejected.map((r) => r.type).join(', ')}` : '',
  ].filter(Boolean);
  return `${result.status}${notes.length ? ` (${notes.join('; ')})` : ''}`;
}

export default function StatePersistenceDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [saved, setSaved] = useState<DataGridState | null>(null);
  const [status, setStatus] = useState('Sort, filter, page, resize or drag a column, then reload the page: the grid comes back as you left it.');
  return (
    <>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            const state = api.current?.getState();
            if (!state) return;
            setSaved(state);
            setStatus('Saved the current state (shown below).');
          }}
        >
          Save state
        </Button>
        <Button
          variant="outline"
          disabled={saved === null}
          onClick={() => {
            if (!api.current || !saved) return;
            setStatus(`Restore: ${describe(api.current.restoreState(saved))}.`);
          }}
        >
          Restore
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            if (!api.current) return;
            // Back to the definition state; also clears the stored entry.
            setStatus(`Reset: ${describe(api.current.resetState())}.`);
          }}
        >
          Reset
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const state = api.current?.getState({ exclude: ['selection', 'scroll'] });
            if (!state) return;
            // URL-safe base64url: put it in a query string to share a view.
            setStatus(`Shareable: ?view=${serializeDataGridState(state)}`);
          }}
        >
          Copy as URL parameter
        </Button>
      </div>
      <DataGrid<Order>
        id="docs-orders-state"
        aria-label="Orders that remember their state"
        data={orders}
        columns={columns}
        persistState={persistState}
        sorting={{ multiple: true }}
        filtering
        paging={{ pageSize: 10, pageSizeOptions: [10, 20, 50] }}
        resizable
        reorderable
        height={360}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
      />
      <p className="demo-status" aria-live="polite" style={{ overflowWrap: 'anywhere' }}>
        {status}
      </p>
      {saved ? (
        <pre className="demo-log" aria-label="Saved state" tabIndex={0}>
          {JSON.stringify(saved, null, 2)}
        </pre>
      ) : null}
    </>
  );
}
```

## API reference

See [`DataGridPersistState`](https://salmonui.dev/docs/reference/data-grid/DataGridPersistState),
[`DataGridState`](https://salmonui.dev/docs/reference/data-grid/engine/DataGridState),
[`RestoreResult`](https://salmonui.dev/docs/reference/data-grid/engine/RestoreResult) and
[`createSavedViews`](https://salmonui.dev/docs/reference/data/views/createSavedViews) in the API
reference.
