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:
| Field | Contents |
|---|---|
columnWidths | Widths of columns whose width was set (only columns widened by hand / auto-sized / set with applyState; columns still on width / flex aren't included) |
filters | The search text of the top bar (globalText) and the column filters (columnFilters) |
sort | The sort columns and directions (multiple columns too) |
columns | Column order / visibility / pinning ({ key, visible?, pinned?, rowGroup? }[]; array order = column order. rowGroup only with includeGroupingInState) |
collapsedGroups | Keys of collapsed groups (only with includeGroupingInState. Since 1.2.0) |
closedColumnGroups | Keys of closed column groups (only when columnGroups has collapsible groups (collapsible). Since 1.6.0) |
closedTreeRows | Keys of closed parent rows in tree data (only with treeData; opening and closing while filtered isn't included. Since 1.9.0) |
page / pageSize | The 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)
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 holdingShift), filtering, column widths or column order (drag a header), and the value received inonStateChangegoes into "Saved value" below. - You can group with "Group by this column" in the column menu (
⋮) of "Category". WhileincludeGroupingInStateis 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
initialStateandrestoreColumnsFromState(the screen before restoring is never shown). The demo saves to React state; a real app saves tolocalStorageor a server.
Saving (onStateChange / getState)
<SpreadsheetGrid
rows={rows}
columns={columns}
onColumnsChange={setColumns}
onStateChange={(state) => localStorage.setItem('orders-grid', JSON.stringify(state))}
/>onStateChangeis 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 canJSON.stringifyit 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))}
/>initialStateis used only once, on mount. It takes effect from the first render, so the screen before restoring never flashes (with serverSide, from the firstgetRows). Passing it again later changes nothing.initialStatedoesn't use column order / visibility / pinning (columns). For those,restoreColumnsFromState(columns, saved)makes an array applied to your column definitions, which you pass to thecolumnsprop. 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 tocolumns). - The
localStorageexample above is for screens drawn only in the browser. On pages rendered on a server (Next.js App Router and the like), don't readlocalStorageduring 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. Forfilters, you can pass just one ofglobalText/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 anonColumnsChange. If it matches the current columns,onColumnsChangeisn't called (since 1.3.0).onStateChangeis called afterapplyStatetoo (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,
onStateChangeisn't called, so the old keys stay in your saved value. To remove them, save again with the value ofgetState()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.
versionis the version of the saved shape (currently2). The old shape withoutcolumns(version: 1) is loaded without touching column order.- The value (
value) of acustomfilter goes in as is, so keeping it JSON-serializable is up to your app.
Restoring from the URL
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 readssearchParamsinside<Suspense>(a Next.js rule). Wrap it inside the page, not inlayout.tsx. - To update the URL when users sort, call
router.replaceinonSortChange/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
columnsthat hasrowGroupwritten getsrowGroup(true/false). "Group by this column" and "Ungroup" in the column menu are included too. The grouping hierarchy follows column order, sorestoreColumnsFromStaterestores it together with the order. collapsedGroupsholds an array of collapsed group keys, andonStateChangeis 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 incollapsedGroups(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 ingetGroupRows()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 insetColumns(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(). Thecollapsedof each group ingetGroupRows()tells you whether it's collapsed.
Method and type details are in "Saving / restoring state" in Imperative API.