

## Overview [#overview]

Use `useDataGridView` when users need to save and restore a grid configuration.
A view can include filters, column visibility, order and pinning, sorting,
grouping, and pivoting when those features are enabled. Pivot preferences such
as [source-row visibility](/components/data-grid/pivoting#summary-only-views)
are included.

Transient state is excluded, including records, column sizing, selection,
focus, editing, expansion, row pinning, and virtualization. The consumer owns
view names, permissions, defaults, URLs, and storage.

## Example [#example]

This example uses one filter definition for the control, codec, and table.
Change the grid, save its current view, then restore it.

<Tabs items="['Preview', 'Code']">
  <Tab value="Preview">
    <Preview name="DataGridViewStateScenario" />
  </Tab>

  <Tab value="Code">
    ```tsx
    const defaultView = {
      version: 1,
      filters: [],
      columns: {
        order: [],
        pinning: { start: [], end: [] },
        visibility: {},
      },
      sorting: [],
      grouping: [],
    } satisfies DataGridViewState<typeof definition>;

    const codec = createDataGridViewCodec({
      defaultView,
      filterDefinition: definition,
    });

    function MattersGrid() {
      const view = useDataGridView({ columns, codec, initialView: defaultView });
      const table = useDataGridTable(
        {
          columns: view.columns,
          data: matters,
          enableColumnReordering: true,
          getRowId: (row) => row.id,
          ...view.tableOptions,
        },
        () => null,
      );
      const filtersControl = useDataGridFiltersControl(table);

      const saveCurrentView = () => {
        const state = table.dataGridView.capture();
        saveView(table.dataGridView.codec.encode(state));
      };

      return (
        <Filters.Root {...filtersControl}>
          <div className="flex flex-wrap items-center gap-2.5">
            <Filters.Trigger />
            <Filters.Items />
          </div>
          <DataGrid table={table}>
            <DataGrid.Viewport aria-label="Matters with saved views" />
          </DataGrid>
          <Button onClick={saveCurrentView}>Save current view</Button>
        </Filters.Root>
      );
    }
    ```
  </Tab>
</Tabs>

Use `capture()` to read the current view and `encode()` or `stringify()` to
prepare it for storage or a URL. Use `restore()` for untrusted stored input;
it validates the value, removes stale configuration, applies the result, and
reports whether it was unchanged, reconciled, or replaced by a fallback.

Use `reconcile()` to inspect input without changing the table and `apply()`
only for an already typed view. `subscribe()` observes durable view changes and
returns its cleanup function; it does not persist them.

## API Reference [#api-reference]

### useDataGridView [#usedatagridview]

Prepare the columns and table options required for durable views, then pass
both results to `useDataGridTable`.

| Option              | Type                                            | Default                     | Description                                                            |
| ------------------- | ----------------------------------------------- | --------------------------- | ---------------------------------------------------------------------- |
| `columns`           | `readonly DataGridColumnDef<TData>[]`           | -                           | Stable source columns. Required.                                       |
| `codec`             | `DataGridViewCodec<TDefinition>`                | -                           | Codec for the view shape and optional Filters definition. Required.    |
| `initialView`       | `DataGridViewState<TDefinition>`                | Codec default or empty view | Initial view reconciled against the table.                             |
| `filteringStrategy` | `"client" \| "server"`                          | `"client"`                  | Selects client or server filtering.                                    |
| `filters`           | `DataGridViewFilterOptions<TData, TDefinition>` | -                           | Optional field mappings, evaluators, faceting, and hierarchy settings. |

### createDataGridViewCodec [#createdatagridviewcodec]

| Option             | Type                             | Default | Description                                                    |
| ------------------ | -------------------------------- | ------- | -------------------------------------------------------------- |
| `defaultView`      | `DataGridViewState<TDefinition>` | -       | Supplies the default initial view and reconciliation fallback. |
| `filterDefinition` | `TDefinition`                    | -       | Adds typed Cubitt Filters state to the view codec.             |

### table.dataGridView [#tabledatagridview]

| API         | Signature or type                                               | Description                                                                |
| ----------- | --------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `capture`   | `() => DataGridViewState<TDefinition>`                          | Returns a detached snapshot of the current durable view.                   |
| `reconcile` | `(input, options?) => DataGridViewReconcileResult<TDefinition>` | Validates and repairs input against the current table without applying it. |
| `apply`     | `(state: DataGridViewState<TDefinition>) => void`               | Applies an already typed view.                                             |
| `restore`   | `(input, options?) => DataGridViewRestoreResult<TDefinition>`   | Reconciles untrusted input, applies the result, and returns diagnostics.   |
| `subscribe` | `(listener) => () => void`                                      | Observes durable view changes and returns a cleanup function.              |
| `codec`     | `DataGridViewCodec<TDefinition>`                                | Codec installed for the table.                                             |

### View types and codec [#view-types-and-codec]

| Export                                     | Type                                       | Description                                                       |
| ------------------------------------------ | ------------------------------------------ | ----------------------------------------------------------------- |
| `DataGridViewState<TDefinition>`           | Readonly versioned object                  | JSON-safe durable view state.                                     |
| `DataGridViewCodec<TDefinition>`           | Codec object                               | Type returned by `createDataGridViewCodec`.                       |
| `DataGridViewReconcileResult<TDefinition>` | Discriminated result                       | Reports `unchanged`, `reconciled`, or `fallback` with any issues. |
| `DataGridViewRestoreResult<TDefinition>`   | `DataGridViewReconcileResult<TDefinition>` | Result returned after restoring untrusted input.                  |
| `DataGridViewReconcileIssue`               | `{ slice, code, id? }`                     | Identifies a stale, invalid, or unsupported view entry.           |
| `DataGridViewTransport<TDefinition>`       | Saved-view API object                      | Type of `table.dataGridView`.                                     |

### Codec methods [#codec-methods]

| API               | Signature                                              | Description                                             |
| ----------------- | ------------------------------------------------------ | ------------------------------------------------------- |
| `codec.encode`    | `(state) => JsonValue`                                 | Returns detached canonical JSON for structured storage. |
| `codec.stringify` | `(state) => string`                                    | Returns canonical text for URL or string storage.       |
| `codec.parse`     | `(input) => DataGridViewCodecParseResult<TDefinition>` | Parses untrusted input without reading the table.       |
| `codec.equals`    | `(left, right) => boolean`                             | Compares two views by their canonical representation.   |
