Undo and redo
Undo and redo edits, pastes, fills, and row operations with Ctrl+Z and Ctrl+Y, or with your own toolbar buttons.
A user who pastes over the wrong cells needs a way back. The data-grid-history add-on keeps a stack of changes and reverts them. useDataGridState gives a grid undo and redo in one call. useDataGridHistory adds the same stack to a grid whose data you own.
Edit a cell, then undo/redo with the buttons below or Ctrl+Z / Ctrl+Y (Cmd on Mac).
pnpm dlx shadcn@latest add @gridcn/data-grid-history
How it works
Each entry on the stack is one change: the operations (ops) of one onDataChange call. A paste, a fill, and the delete of a range are one entry each. Operations address rows by row id, so an entry finds its row again after a sort or a filter moves it.
Undo applies the inverse of the most recent entry as one change with source: "history". Redo applies the entry again. A new change clears the redo stack.
If a row that the entry needs is missing from the data, undo and redo apply nothing. A refresh that removed the row causes this. See Rows that are not loaded or gone.
Quick start: useDataGridState
useDataGridState is the short path to undo and redo. It owns the data array and passes it to the grid as the controlled data prop. Each undo writes through the grid, and the hook stores the result. Spread the result onto DataGrid:
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import { useDataGridState } from "@/components/data-grid-history/data-grid-history";
type Row = { id: string; name: string };
const rows: Row[] = [{ id: "1", name: "Ada" }];
const columns = defineColumns<Row>()([
{ id: "name", header: "Name", accessorKey: "name" },
]);
function MyGrid() {
const grid = useDataGridState(rows);
const { canUndo, canRedo, undo, redo } = grid.history;
return (
<>
<button disabled={!canUndo} onClick={undo}>Undo</button>
<button disabled={!canRedo} onClick={redo}>Redo</button>
<DataGrid {...grid} columns={columns} />
</>
);
}Result: edit a cell, then press Undo. The cell returns to its earlier value and Redo turns on.
Undo and Redo write only the cells of the entry onto the current row. A value in another column that changed after the edit, for example from a stream push or a refetch, stays. An update that you build for record without a cells list writes the whole row.
getRowId defaults to the id field of a row. grid.history holds canUndo, canRedo, historySize, undo, redo, clear, record, and rollback. historySize counts the entries on the undo stack. clear empties both stacks.
To mount other plugins, pass them in the plugins option: useDataGridState(rows, { plugins: [fill.plugin] }). The returned grid.plugins holds them and the history plugin. A plugins prop after the spread replaces the history plugin. An inline plugin object is a new plugin on every render, so define it at module scope or memoize it. In development, undo, redo, record, and rollback warn once when the plugin never mounted.
Keyboard
- Ctrl/Cmd+Z undoes.
- Ctrl/Cmd+Y and Ctrl/Cmd+Shift+Z redo.
The keys work while focus is in the grid. While a cell editor is open, the editor keeps them for its own text. Without this add-on, the grid leaves both keys to the browser. Remap them with the undo and redo actions of the keymap prop.
When you mount DataGridGlobalShortcuts, the keys also work while focus is outside the grid. They skip text fields.
Composable: useDataGridHistory
If you own the data array, call useDataGridHistory and pass its plugin to the grid. Your onDataChange keeps feeding your state. The hook records each change after your handler runs:
import { useState } from "react";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import { useDataGridHistory } from "@/components/data-grid-history/data-grid-history";
type Row = { id: string; name: string };
const rows: Row[] = [{ id: "1", name: "Ada" }];
const columns = defineColumns<Row>()([
{ id: "name", header: "Name", accessorKey: "name" },
]);
function MyGrid() {
const [data, setData] = useState<readonly Row[]>(rows);
const history = useDataGridHistory<Row>({ capacity: 50 });
return (
<>
<button disabled={!history.canUndo} onClick={history.undo}>Undo</button>
<DataGrid
data={data}
columns={columns}
onDataChange={setData}
plugins={[history.plugin]}
/>
</>
);
}The result has the members of grid.history above, plus plugin. useDataGridHistory also works when the grid owns the data with defaultData. A grid with defaultData and no history plugin keeps no history.
Capped stack
capacity limits the entries on the undo stack. The default is 100. When the stack is full, the oldest entries drop first. capacity counts entries, not operations: a paste of 10,000 cells is one entry.
Read-only grids
A readOnly grid refuses writes, so it records nothing. The keys, undo, and redo do nothing and keep their entries. canUndo and canRedo are false while the grid is readOnly. historySize still counts the entries.
Server mode
Undo works in every data mode. Entries address rows by row id, so they follow server sort and server filter. In server pagination, data holds one page. An undo or redo for a row of another page keeps its entry and reports "rows-not-loaded" to onSkip. It applies when the page shows again.
onSave receives an undo or a redo as a change with source: "history". Your handler sends the inverse change to the server like any other change. If onSave refuses all or part of a change, the grid reverts the refused rows. See Refused undo and redo.
If your onDataChange writes to your backend and you pass no onSave, the stack does not learn whether the server accepted the write. After a failed save, call rollback(change).
Rows that are not loaded or gone
An update, delete, or move needs its row in data. An insert needs no row. If a row is missing, undo and redo apply nothing, and the live region announces the block. What happens to the entry depends on why the row is missing:
| Case | Entry | onSkip reason |
|---|---|---|
Every needed row is in data | applied | none |
A needed row is missing, and data has holes (scroll mode) or holds part of the result (server pagination) | stays on its stack | "rows-not-loaded" |
A needed row is gone from data, which holds the whole result | dropped | "rows-gone" |
For "rows-not-loaded", load the rows or show their page, and call undo again. Until the rows load, datasetKey changes, or clear() runs, the entry blocks the older entries under it. Pass onSkip to react:
import { toast } from "sonner";
import {
useDataGridHistory,
type HistorySkip,
} from "@/components/data-grid-history/data-grid-history";
type Row = { id: string; name: string };
export function useHistoryWithHint() {
return useDataGridHistory<Row>({
onSkip: ({ direction, reason, rowIds }: HistorySkip) => {
if (reason === "rows-not-loaded") {
toast(`Scroll to load ${rowIds.length} rows, then ${direction} again`);
}
},
});
}onSkip receives { direction, reason, rowIds }. direction is "undo" or "redo", and rowIds lists the missing rows. A throw in onSkip is logged and isolated. A datasetKey change clears both stacks without calling onSkip.
Refused undo and redo
If onSave refuses a change, the grid reverts the refused rows with a "rollback" change. The entry then follows this table:
onSave refused | The revert | The entry |
|---|---|---|
| An ordinary change | writes | leaves the stacks |
| An undo | writes | returns to the undo stack |
| A redo | writes | returns to the redo stack, unless a newer undo entry sits above it |
| Any change | writes nothing, because the grid is readOnly or a newer edit replaced every refused value | stays where it is |
Rows the server replaced
- A save conflict that takes the server row, or a rollback or merge change with
serverRowIds, replaces the content of those rows. History removes the operations on those rows from all older entries. An entry left with no operations goes. See Handle refused saves. actions.replaceRowId(oldId, row)swaps a server-assigned id into a row. History rewrites the older entries to the new id, so an earlier edit still undoes. History does not record the swap.
Options
| Prop | Type | Default |
|---|---|---|
capacity | number | 100 |
datasetKey | string | number | ((spec: ServerSpec) => string | number) | none |
onSkip | (ctx: { direction; reason; rowIds }) => void | none |
recordSources | readonly DataChange<TData>["source"][] | ((defaults) => readonly DataChange<TData>["source"][]) | edit, paste, fill, delete, cut, row-operation, import, replace, and app |
useDataGridState takes getRowId and every option of useDataGridHistory. Undo for code changes explains recordSources and datasetKey. Undo with server data shows the function form.
Related
Fill handle
Drag the corner of a selection to copy it or continue a number or text series, or fill down and right from the keyboard.
Undo for code changes
Make changes that your code applies undoable with record or a change source, pick which sources the history keeps, and reset it when you swap the data.