# Updating data

> Replace rows with setRows, apply incremental changes with applyTransaction, change any option with update(), and know when to refresh or redraw.

The grid owns no data of its own. It renders the rows you pass and re-runs its pipeline (filter, sort, paginate and any module stages) whenever you tell it the data changed. There are three ways to do that, from coarse to fine.

| You want to | Use | Keeps selection, focus and scroll |
| --- | --- | --- |
| Load a new dataset | `setRows(rows)` or `update({ rows })` | Yes, for rows whose ID survives |
| Add, change or remove a few rows | `applyTransaction({ add, update, remove })` | Yes |
| Change any other option | `update({ ...partial })` | Yes |
| Re-render after mutating a row object in place | `refresh()` | Yes |

## Replacing all rows: setRows

```ts title="load-orders.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

const grid = createGrid<Order>(document.querySelector('#orders')!, {
  columns,
  rows: [],
  getRowId: (order) => order.id,
  emptyMessage: 'Loading orders…',
});

async function loadOrders(region: string) {
  const response = await fetch(`/api/orders?region=${encodeURIComponent(region)}`);
  grid.setRows(await response.json());
}

await loadOrders('EMEA');
```

`setRows()` keeps the current sort, filters, quick filter and column state, and keeps the current page when it still exists. With `getRowId`, selected rows stay selected if they are still present. Selected rows that are missing from the new data are deselected, and `selectionChanged` fires when that happens.

`setRows(rows)` is shorthand for `update({ rows })`, which is what framework adapters call when the `rows` prop changes.

> **Pass a new array**
>
> `update()` only applies keys whose value changed by identity. Calling `setRows(rows)` with the same array you passed before, even after pushing to it, does nothing. Pass a new array (`setRows([...rows])`), or use `applyTransaction()` for incremental changes.

## Incremental changes: applyTransaction

A transaction adds, updates and removes rows in one pass and one re-render. It is the right tool for live feeds, websocket pushes and optimistic UI.

```ts
grid.applyTransaction({
  add: [{ id: 'SO-10431', customer: 'Fjord Outfitters', region: 'EMEA', orderDate: '2026-03-09', quantity: 20, revenue: 9100, status: 'Pending' }],
  update: [{ ...grid.getRowById('SO-10422')!, status: 'Shipped' }],
  remove: ['SO-10398', 'SO-10401'],
});
```

**`RowTransaction`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface RowTransaction<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `add?` | `TRow[]` |  |
| `update?` | `TRow[]` |  |
| `remove?` | `(TRow \| string)[]` |  |

The parts run in a fixed order:

1. **remove** takes row objects or row IDs. Rows that are not present are ignored.
2. **update** replaces existing rows, matched by ID, keeping their position in the source order. Rows that do not match an existing ID are ignored.
3. **add** appends new rows to the end of the source rows. Sorting still decides where they appear.

Removed rows also leave the selection, and `selectionChanged` fires if any of them was selected.

> **Updates need stable IDs**
>
> `update` finds rows by ID. With `getRowId`, a freshly built object such as `{ ...row, status: 'Shipped' }` matches the existing row. Without `getRowId`, IDs are tied to object instances, so only the original objects match. Set `getRowId` for any grid that receives updates.

### Streaming updates

Batch high-frequency messages and apply them once per animation frame:

```ts
const pending: Order[] = [];
let scheduled = false;

socket.addEventListener('message', (event) => {
  pending.push(JSON.parse(event.data));
  if (scheduled) return;
  scheduled = true;
  requestAnimationFrame(() => {
    grid.applyTransaction({ update: pending.splice(0) });
    scheduled = false;
  });
});
```

## Changing options: update()

`update(partial)` applies only the keys you pass and never recreates the grid. Anything in `GridOptions` can change at runtime.

```ts
grid.update({ theme: 'dark', density: 'compact' });
grid.update({ quickFilter: 'kestrel' });
grid.update({ sort: [{ colId: 'revenue', dir: 'desc' }] });
grid.update({ pagination: { pageSize: 50 } });
```

Keys you leave out keep their current value, and keys whose value is identical to the current one are skipped. To clear an option, pass its empty value explicitly, for example `update({ quickFilter: '' })` or `update({ filterModel: {} })`. Read the current options with `getOptions()`.

Changing `pagination` returns to the page given in it, or to the first page. State options applied through `update()` fire the same events as the dedicated methods: `sort` fires `sortChanged`, and `filterModel` or `quickFilter` fire `filterChanged` and return to the first page. Changing `modules` uninstalls modules that are no longer listed and installs new ones.

## Changing columns

Replace the column list with `setColumns(columns)` or `update({ columns })`. The grid keeps user changes (width, pinning, visibility and order) for every column whose ID still exists, so you can add a column without resetting the layout the user arranged.

```ts
const withMargin: ColumnDef<Order>[] = [
  ...columns,
  { id: 'margin', header: 'Margin', type: 'number', valueGetter: (o) => o.revenue - o.cost },
];
grid.setColumns(withMargin);
```

To reset the layout instead, apply a saved column state or the defaults. See [Column operations](https://docs.birchui.com/grid/column-operations.md#saving-and-restoring-column-state).

## Editing values from code

`setValue(row, colId, value, source?)` writes through the column's `valueSetter` or `field`, re-renders the row and fires `cellValueChanged` with `source: 'api'` unless you pass another source. It returns `false`, and fires nothing, when the column does not exist, when the new value is identical to the current one, or when the `valueSetter` throws.

```ts
const order = grid.getRowById('SO-10423')!;
grid.setValue(order, 'status', 'Shipped');
```

## Mutating rows in place: refresh and redraw

If you change a row object directly, the grid cannot know. Call one of:

- `refresh()` re-runs the row pipeline (filter, sort, module stages, pagination) and re-renders. Use it after in-place mutations that can affect sorting or filtering.
- `redraw()` re-renders the header and every visible cell without re-running the pipeline. Use it after changing something that only affects rendering, such as a lookup table a cell renderer reads.

```ts
const order = grid.getRowById('SO-10421')!;
order.revenue = 19250;
grid.refresh();

exchangeRates.EUR = 1.09;
grid.redraw();
```

> **Tip**
>
> Prefer `applyTransaction({ update: [...] })` or `setValue()` over mutate-then-refresh. They tell the grid exactly which rows changed, keep the quick filter's cached search text in sync and fire the right events. After an in-place mutation, the quick filter may still match the row's old text until the row is replaced.

## Knowing when the model changed

`modelUpdated` fires after every pipeline run with the number of source rows and display rows:

```ts
grid.on('modelUpdated', ({ rowCount, displayRowCount }) => {
  summary.textContent = `${displayRowCount} of ${rowCount} orders`;
});
```

## Related

- [Rows & row IDs](https://docs.birchui.com/grid/rows.md)
- [Editing](https://docs.birchui.com/grid/editing.md) for user edits and `cellValueChanged`
- [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md) for very large or fast-changing datasets
