# Table state and editing

Keep sorting, selection, and edits in sync with your app.

## Sync sorting with your app

Control sorting when it must stay in sync with a URL, server request, or another view. Pass both the current sort and its change handler. The handler can receive a new value or an updater function. Use initialState when the table should manage subsequent changes.

```tsx
import { useState } from "react";
import { createSortedRowModel, rowSortingFeature, tableFeatures, useTable, type ColumnDef, type SortingState } from "@tanstack/react-table";
import { Table } from "@collectivecreation/ghost-ui/components/table";
import { Button } from "@collectivecreation/ghost-ui/components/button";

type Source = { id: string; title: string };
const features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel() });
const rows: Source[] = [{ id: "b", title: "Beta" }, { id: "a", title: "Alpha" }];
const columns: ColumnDef<typeof features, Source>[] = [{
  accessorKey: "title",
  header: ({ column }) => <Button variant="ghost" onClick={() => column.toggleSorting()}
    aria-label={`Sort sources: ${column.getIsSorted() || "unsorted"}`}>Source</Button>,
}];
export function SortedSources() {
  const [sorting, setSorting] = useState<SortingState>([]);
  const table = useTable({ features, data: rows, columns, getRowId: row => row.id,
    state: { sorting }, onSortingChange: setSorting });
  return <Table aria-label="Sources"><Table.Data table={table} /></Table>;
}

```

Outside Ghost's subscribed renderers, use table.Subscribe or TanStack's selector hooks for reactive reads. Adding an engine feature does not add its surrounding controls: compose those in the application.

## Reuse a table instance in Data grid

Pass table to DataGrid to retain the same data, accessor and feature configuration. columnDef.meta.dataGrid adds editable, validate, renderEditor, or other grid policies. The grid adapts the instance's current row model and visible/pinned columns; avoid keeping a parallel filtered row list. Instance mode binds supported sorting, sizing, order and visibility methods; supplied callbacks also receive the requests.

For a small grid, pass rows as stable { id, data } records. An edit gives you a string draft even for a numeric column. Parse and validate it before changing the record.

```tsx
import { useState } from "react";
import { DataGrid, type DataGridRow, type DataGridColumn } from "@collectivecreation/ghost-ui/components/data-grid";
type Source = { title: string };
const columns: DataGridColumn<Source>[] = [{ id: "title", label: "Source", editable: true,
  validate: value => value.trim() ? undefined : "Enter a source name" }];
export function EditableSources() {
  const [rows, setRows] = useState<DataGridRow<Source>[]>([{ id: "handbook", data: { title: "Handbook.pdf" } }]);
  return <DataGrid ariaLabel="Sources" rows={rows} columns={columns}
    onCellEdit={({ rowId, value }) => setRows(current => current.map(row =>
      row.id === rowId ? { ...row, data: { title: value } } : row))} />;
}

```

The grid handles focus, selection, and the draft while a cell is open. A custom renderEditor receives the draft and the onChange, commit, and cancel callbacks. Use onEditStateChange to show surrounding feedback.

Treat onCellEdit as a request to update your rows. If saving takes time, show pending and error states in your app. Keep the previous value for rollback and ignore a late response if a newer edit superseded it. Check write permission on the server.

## Choose client or server operations

Client operations apply to the rows already loaded. To sort or filter the entire dataset on a server, pass manualSorting or manualFiltering and return the processed rows. Use manualPagination for server paging and supply the row or page count. Include the controlled state in the request key so changing it fetches the correct page.

Abort or ignore superseded requests. Decide whether off-page selections persist and resolve selected IDs against your backend before an operation. Stable IDs do not imply that an off-page row is loaded. Reordering requests are meaningful only when the application allows an ordering independent of the current sort/filter.

## When to pass your own instance

The raw rows and columns API reports sort, hide, and reorder requests. Pass your own TanStack instance for filtering, paging, or more feature controls. Use paging or a separate virtualized view to bound the number of rows you render.

See [Data grid API](/components/data-grid#api-reference), [Table API](/components/table#api), and [TanStack controlled state](https://tanstack.com/table/latest/docs/framework/react/guide/table-state).
