SpreadsheetGrid
Guides

Saving and restoring state

Save the column widths, filters, sorting and column order / visibility / pinning users changed, and bring them back next time (getState / applyState / initialState / restoreColumnsFromState)

The "view of the table" users build on screen can be taken out as a GridState, saved, and brought back the next time they open it. It contains:

FieldContents
columnWidthsWidths of columns whose width was set (only columns widened by hand / auto-sized / set with applyState; columns still on width / flex aren't included)
filtersThe search text of the top bar (globalText) and the column filters (columnFilters)
sortThe sort columns and directions (multiple columns too)
columnsColumn order / visibility / pinning ({ key, visible?, pinned?, rowGroup? }[]; array order = column order. rowGroup only with includeGroupingInState)
collapsedGroupsKeys of collapsed groups (only with includeGroupingInState. Since 1.2.0)
closedColumnGroupsKeys of closed column groups (only when columnGroups has collapsible groups (collapsible). Since 1.6.0)
closedTreeRowsKeys of closed parent rows in tree data (only with treeData; opening and closing while filtered isn't included. Since 1.9.0)
page / pageSizeThe current page (0-based) and rows per page of pagination (only with pagination. Since 1.15.0)

Not included: the active cell, selection, scroll position, an edit in progress, and row selection. Row grouping (the column's rowGroup) and the open state of groups are included only with includeGroupingInState ("Saving row grouping" below). The row data (rows) belongs to your app, so save it separately.

Demo (reopen and it comes back)

Times opened: 1
Rows 40 of 40Columns 4 of 4Sort: —
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Rows 40 of 40Columns 4 of 4
Cell —Range —0 cells / 0 rows0 columns
Saved value (the GridState from onStateChange)
(Nothing yet. Change the sort, filters, column widths, column order or grouping from the Type column menu to fill it)
  • Change the sorting (the header's ⋮, or press a header while holding Shift), filtering, column widths or column order (drag a header), and the value received in onStateChange goes into "Saved value" below.
  • You can group with "Group by this column" in the column menu (⋮) of "Category". While includeGroupingInState is on, grouping and the open state of groups are saved too and come back when you reopen (since 1.2.0).
  • "Reopen the table" recreates the grid and restores the saved value with initialState and restoreColumnsFromState (the screen before restoring is never shown). The demo saves to React state; a real app saves to localStorage or a server.

Saving (onStateChange / getState)

<SpreadsheetGrid
  rows={rows}
  columns={columns}
  onColumnsChange={setColumns}
  onStateChange={(state) => localStorage.setItem('orders-grid', JSON.stringify(state))}
/>
  • onStateChange is called only when what it contains actually changes. It isn't called while dragging a column width, only once on release. It isn't called on the first mount or on changes of the active cell or selection.
  • To save from a save button, get the current value with the handle's getState() (it's a new object, so you can JSON.stringify it as is).
  • To follow only filters and sorting (to build a server query, for example), use onFiltersChange / onSortChange. They aren't called on changes of column width or order.

Restoring on open (initialState / restoreColumnsFromState)

const [initialState] = useState(() => {
  const saved = localStorage.getItem('orders-grid');
  return saved ? JSON.parse(saved) : undefined;
});
const [columns, setColumns] = useState(() => restoreColumnsFromState(defaultColumns, initialState));

<SpreadsheetGrid
  rows={rows}
  columns={columns}
  onColumnsChange={setColumns}
  initialState={initialState}
  onStateChange={(state) => localStorage.setItem('orders-grid', JSON.stringify(state))}
/>
  • initialState is used only once, on mount. It takes effect from the first render, so the screen before restoring never flashes (with serverSide, from the first getRows). Passing it again later changes nothing.
  • initialState doesn't use column order / visibility / pinning (columns). For those, restoreColumnsFromState(columns, saved) makes an array applied to your column definitions, which you pass to the columns prop. Columns not in the saved value (added later) go at the end, and saved columns not in the current definitions are dropped. When there is no saved value or it can't be read, the array you passed is returned as is.
  • Letting users reorder columns needs onColumnsChange (pass the array you receive back to columns).
  • The localStorage example above is for screens drawn only in the browser. On pages rendered on a server (Next.js App Router and the like), don't read localStorage during render; pass it from the URL or the server ("Restoring from the URL" below).

Restoring later (applyState)

To restore after mounting, use the handle's applyState(state). It suits a "choose a saved view" menu or a "reset" button.

gridRef.current?.applyState(JSON.parse(saved));                    // everything
gridRef.current?.applyState({ sort: [{ columnKey: 'qty', direction: 'desc' }] }); // sorting only
gridRef.current?.applyState({ filters: { columnFilters: {} } });   // clear only the column filters
  • Only what you pass changes. Anything omitted (undefined) stays as it is. For filters, you can pass just one of globalText / columnFilters.
  • It's applied in one render (passing filters and sorting together shows no intermediate screen). getState() right after returns the new value.
  • columns (column order / visibility / pinning) is applied only when there is an onColumnsChange. If it matches the current columns, onColumnsChange isn't called (since 1.3.0).
  • onStateChange is called after applyState too (it may save the same value again, which is harmless).

Changed columns and broken values

Saved values are loaded even after you change the column definitions. The grid treats old values as follows.

  • Widths, column filters and sorting of columns not in the current columns are dropped (with a warning in development). If dropping them doesn't change the current state, onStateChange isn't called, so the old keys stay in your saved value. To remove them, save again with the value of getState() after restoring.
  • Broken values (non-numeric widths, column filters of the wrong shape, unknown sort directions, duplicate column keys) are dropped piece by piece and the rest is used. Passing hand-written values or values from old versions doesn't crash.
  • version is the version of the saved shape (currently 2). The old shape without columns (version: 1) is loaded without touching column order.
  • The value (value) of a custom filter goes in as is, so keeping it JSON-serializable is up to your app.

Restoring from the URL

React onlyThe example uses the Next.js App Router. In Solid, pass the value read from the URL to initialState on the first render (the same as the Solid tab of Saving).

Put sorting and filtering in the URL, and a shared link opens the same view. initialState takes effect from the server render, so with the Next.js App Router you can read the URL in a server component and pass it.

// app/orders/page.tsx (server component. OrdersGrid renders SpreadsheetGrid with 'use client')
import { Suspense } from 'react';

export default function Page({ searchParams }: { searchParams: Promise<{ sort?: string }> }) {
  return (
    <Suspense>
      <Orders searchParams={searchParams} />
    </Suspense>
  );
}

async function Orders({ searchParams }: { searchParams: Promise<{ sort?: string }> }) {
  const [columnKey, direction] = ((await searchParams).sort ?? '').split('.');
  const initialState = columnKey
    ? { sort: [{ columnKey, direction: direction === 'desc' ? ('desc' as const) : ('asc' as const) }] }
    : undefined;
  return <OrdersGrid initialState={initialState} />;
}
  • With Next.js 16's cacheComponents, put the part that reads searchParams inside <Suspense> (a Next.js rule). Wrap it inside the page, not in layout.tsx.
  • To update the URL when users sort, call router.replace in onSortChange / onFiltersChange.

Saving row grouping

Row grouping (the column's rowGroup) and the open state of groups aren't in GridState by default. Add includeGroupingInState to include them (since 1.2.0).

const [columns, setColumns] = useState(() => restoreColumnsFromState(defaultColumns, saved)); // rowGroup comes back too

<SpreadsheetGrid
  columns={columns}
  onColumnsChange={setColumns}
  initialState={saved}            // collapsed groups come back too
  includeGroupingInState
  onStateChange={save}
/>
  • Each column in columns that has rowGroup written gets rowGroup (true / false). "Group by this column" and "Ungroup" in the column menu are included too. The grouping hierarchy follows column order, so restoreColumnsFromState restores it together with the order.
  • collapsedGroups holds an array of collapsed group keys, and onStateChange is called every time a group opens or closes (which is why it's off by default). Keys not in the current rows have no effect on screen but stay in collapsedGroups (so a group comes back closed when a filter is cleared). In tables whose groups keep changing, the saved value keeps growing, so narrow it to the keys in getGroupRows() before saving.
  • Resetting columns (column menu / tool panel) returns to the columns at mount (the columns restored with restoreColumnsFromState). To return to your app's default columns, pass the columns yourself, as in setColumns(defaultColumns).
  • Group keys are strings made from column keys and values, and they don't change when rows are fetched again. Their internal shape isn't fixed, so don't build them yourself; use saved values or getGroupRows(). The collapsed of each group in getGroupRows() tells you whether it's collapsed.

Method and type details are in "Saving / restoring state" in Imperative API.

On this page