# Saving and restoring state

> Capture the whole grid view as JSON with getState, restore it with setState, and save it whenever it changes.

`getState()` returns the whole view as plain JSON: column order, widths, pinning and visibility, sort, filters, the quick filter, the page, expanded and selected row ids, the focused cell, the scroll position, and state from modules. `setState()` applies any part of it, and `stateChanged` fires once per task after any of these change.

```ts title="orders-grid.ts"
import { createGrid, type GridState } from '@birchui/core';

const STORAGE_KEY = 'orders-grid:v1';

function loadState(): Partial<GridState> | null {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    return saved ? (JSON.parse(saved) as Partial<GridState>) : null;
  } catch {
    return null;
  }
}

const grid = createGrid<Order>(el, { columns, rows: orders, getRowId: (order) => order.id });

const saved = loadState();
if (saved) grid.setState(saved);

function saveState(state: GridState): boolean {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
    return true;
  } catch {
    return false;
  }
}

grid.on('stateChanged', ({ state }) => saveState(state));
```

**`GridState`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridState
```

| Property | Type | Description |
| --- | --- | --- |
| `columns` | `ColumnState[]` |  |
| `sort` | `SortItem[]` |  |
| `filterModel` | `Record<string, FilterModel>` |  |
| `quickFilter` | `string` |  |
| `page` | `number` |  |
| `expandedRowIds` | `string[]` |  |
| `selectedRowIds` | `string[]` |  |
| `focusedCell` | `CellPosition \| null` |  |
| `scroll` | `{ top: number; left: number }` |  |
| `modules` | `Record<string, unknown>` |  |

## What to keep in mind

- **Load rows first.** Selection and expansion refer to row ids, so call `setState()` once the rows are in the grid, and give the grid a `getRowId`.
- **Apply only what you want.** `setState({ columns, sort })` restores the layout and sort but keeps the current filters. Leave out `scroll` and `focusedCell` when you restore state on a different screen size.
- **Custom filters are skipped.** Filters with `type: 'custom'` hold a function and cannot be serialized, so they are left out.
- **Invalid parts are skipped.** A malformed section logs one console warning and the rest is applied, so an old saved state does not break the grid. Version your storage key when your columns change significantly.
- **Saving often is cheap.** `stateChanged` is batched to once per task; debounce it yourself if you send state to a server.

## Column state only

When you only need the column layout, `getColumnState()` and `applyColumnState()` work on the `columns` part, and `columnStateChanged` fires when it changes:

**`ColumnState`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ColumnState
```

| Property | Type | Description |
| --- | --- | --- |
| `colId` | `string` |  |
| `width?` | `number` |  |
| `pinned?` | `'left' \| 'right' \| null` |  |
| `hidden?` | `boolean` |  |
| `order?` | `number` |  |

## State from modules

Modules store their own state under `state.modules[name]`. Grid Pro's side bar, for example, saves which panel is open there. A module registers a provider with `internals.addStateProvider(name, { get, set, subscribe })`; the optional `subscribe(notify)` lets it report its own changes so `stateChanged` fires.

**`GridStateProvider`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridStateProvider
```

| Property | Type | Description |
| --- | --- | --- |
| `get` | `() => unknown` |  |
| `set` | `(value: unknown) => void` |  |
| `subscribe?` | `(notify: () => void) => () => void` |  |

## Related

- [Persist grid state to localStorage](https://docs.birchui.com/recipes/grid-persist-state.md), a complete recipe with a reset button.
- [Column operations](https://docs.birchui.com/grid/column-operations.md)
- [Modules](https://docs.birchui.com/grid/modules.md)
