ProGridSign in

Features

Live data and transactions

Patch individual rows instead of replacing the dataset. Built for feeds that never stop — bidding boards, order books, trading screens — where a handful of rows change several times a second.

Why not just replace the rows

Handing the grid a new array is the right move for a page of results and the wrong one for a feed. A replacement invalidates the whole row model: every visible row re-renders, the totals row re-aggregates the entire filtered dataset, and any cell range the user was holding points at whatever now occupies those positions. At one replacement every twenty seconds nobody notices. At five a second it is the only thing anyone notices.

A transaction says only what moved. The grid patches those rows in place, keeps the rest of the row model intact, and flashes the cells whose values actually changed.

<ProGrid
  ref={gridRef}
  columns={columns}
  data={seedRows}
  getRowId={(order) => order.id}
  liveUpdates={{ batchMillis: 60, flashMillis: 900 }}
/>
Live demo

A ticking feed

Rows update several times a second; every few ticks a new order arrives at the top and the oldest drops off. Sort, filter or group it and watch the updates keep landing underneath.

import { useEffect, useMemo, useRef, useState } from "react"
import { ProGrid, type ProColumnDef, type ProGridHandle } from "@/components/pro-grid"
import { formatCurrency, operationOrders, type OperationOrder } from "@/lib/operations-data"

function StatusCell({ value }: { value: unknown }) {
  const status = String(value)
  return <span className={`order-status order-status--${status.toLowerCase().replaceAll(" ", "-")}`}>{status}</span>
}

const baseColumns: ProColumnDef<OperationOrder>[] = [
  { accessorKey: "id", header: "Order", size: 118, meta: { label: "Order", type: "string" } },
  { accessorKey: "customer", header: "Customer", size: 190, meta: { label: "Customer", type: "string" } },
  {
    accessorKey: "region",
    header: "Region",
    size: 145,
    meta: {
      label: "Region",
      type: "string", filterVariant: "set",
      filterOptions: ["North America", "Europe", "Asia Pacific", "Latin America"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "status",
    header: "Status",
    size: 120,
    cell: ({ getValue }) => <StatusCell value={getValue()} />,
    meta: {
      label: "Status",
      type: "string", filterVariant: "set",
      filterOptions: ["On track", "At risk", "Delayed", "Complete"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "units",
    header: "Units",
    size: 88,
    meta: { label: "Units", type: "number", align: "right", aggregable: true, defaultAgg: "sum" },
  },
  {
    accessorKey: "revenue",
    header: "Revenue",
    size: 128,
    meta: {
      label: "Revenue",
      type: "number",
      align: "right",
      aggregable: true,
      defaultAgg: "sum",
      formatValue: (value) => formatCurrency(Number(value)),
    },
  },
]

/**
 * A stand-in for a bidding/trading feed: rows tick several times a second, new
 * orders arrive at the top and finished ones drop off the bottom — all through
 * `applyTransactionAsync` rather than by replacing `data`.
 */
const liveDemoSeed = operationOrders.slice(0, 40)

const LIVE_TICK_MS = 700

const LIVE_MAX_ROWS = 46

let liveSeq = 0

function nextLiveOrder(): OperationOrder {
  const template = operationOrders[(liveSeq * 17) % operationOrders.length]
  liveSeq += 1
  return {
    ...template,
    id: `ORD-9${String(liveSeq).padStart(4, "0")}`,
    status: "On track",
    units: 20 + Math.round(Math.random() * 380),
    revenue: 2000 + Math.round(Math.random() * 90000),
    margin: 10 + Math.round(Math.random() * 30),
  }
}

export function LiveDataDocsDemo() {
  const gridRef = useRef<ProGridHandle<OperationOrder>>(null)
  const [running, setRunning] = useState(true)
  const [commits, setCommits] = useState(0)

  // Held once and never replaced. The grid treats a new `data` array as
  // authoritative and discards applied transactions, so the seed rows have to
  // stay referentially stable and let the transactions do the moving.
  const [seed] = useState(() => liveDemoSeed)

  useEffect(() => {
    if (!running) return
    let ticks = 0

    const timer = setInterval(() => {
      const grid = gridRef.current
      if (!grid) return
      ticks += 1

      // Reading the live rows back is the point of `getRows` — the demo has no
      // copy of its own, the grid holds the truth.
      const rows = grid.getRows()
      const update: OperationOrder[] = []
      for (let i = 0; i < 6 && rows.length; i++) {
        const row = rows[Math.floor(Math.random() * rows.length)]
        if (update.some((r) => r.id === row.id)) continue
        const drift = 1 + (Math.random() - 0.5) * 0.08
        update.push({
          ...row,
          revenue: Math.round(row.revenue * drift),
          units: Math.max(1, Math.round(row.units * drift)),
          margin: Math.round((row.margin + (Math.random() - 0.5) * 3) * 10) / 10,
        })
      }

      // Every few ticks one order lands and the oldest completes, so adds and
      // removes get exercised alongside the updates.
      const churn = ticks % 5 === 0 && rows.length > 4
      grid.applyTransactionAsync({
        update,
        add: churn ? [nextLiveOrder()] : undefined,
        addIndex: 0,
        remove: churn ? [rows[rows.length - 1].id] : undefined,
      })
    }, LIVE_TICK_MS)

    return () => clearInterval(timer)
  }, [running])

  const live = useMemo(
    () => ({
      batchMillis: 80,
      flashMillis: 650,
      maxRows: LIVE_MAX_ROWS,
      onFlush: () => setCommits((n) => n + 1),
    }),
    [],
  )

  return (
    <>
      <div className="docs-demo__status" aria-live="off">
        <span>{running ? "Feed running — changed cells flash" : "Feed paused"}</span>
        <span>
          {commits} commit{commits === 1 ? "" : "s"} ·{" "}
          <button type="button" className="underline" onClick={() => setRunning((r) => !r)}>
            {running ? "Pause" : "Resume"}
          </button>
        </span>
      </div>
      <ProGrid<OperationOrder>
        ref={gridRef}
        columns={baseColumns}
        data={seed}
        getRowId={(row) => row.id}
        height={390}
        liveUpdates={live}
        title="Live order feed"
        toolbar={{ pivot: false, chart: false, refresh: false }}
      />
    </>
  )
}
Feed running — changed cells flash0 commits ·

Live order feed

Order
Customer
Region
Status
Units
Revenue
Total
Sum8580
Sum$1,742,820
40 rows

Transactions

A transaction carries any combination of add, update and remove, applied in the order remove → update → add. That order is what lets a remove and an add of the same id read as a move rather than cancelling out.

gridRef.current.applyTransaction({
  update: [{ ...order, price: 41.2 }],  // matched by id, whole rows
  add: [newOrder],                      // inserted at addIndex
  addIndex: 0,
  remove: ["ORD-10482"],                // rows or row ids
})
// → { status: "applied", add, remove, update, unmatched }
  • update takes whole rows, not partial patches — merge against what you already hold before sending.
  • An update or remove for a row the grid hasn't loaded is reported back in unmatched rather than silently inserted or ignored.
  • An add carrying an id that is already loaded is treated as an update. Two rows under one id would break React keys and row selection alike.
  • Sort order is not recomputed. An inserted row lands where addIndex puts it and stays there until the user re-sorts — the same behaviour every server-backed grid has, because the server owns the ordering.

Batching a real feed

applyTransactionAsync queues rather than commits. Everything queued inside batchMillis is merged into a single transaction, so a socket pushing sixty frames a second still only re-renders about sixteen times. Use it for anything feed-driven and keep applyTransaction for one-off edits, where you want the result back straight away.

useEffect(() => {
  const socket = new WebSocket(FEED_URL)
  socket.onmessage = (event) => {
    const rows = JSON.parse(event.data)
    // Queued, not applied — everything inside batchMillis commits at once.
    gridRef.current?.applyTransactionAsync({ update: rows })
  }
  return () => socket.close()
}, [])

The grid owns no transport. There is no socket, no EventSource and no polling inside it — wire up whichever you have and push what it reports in through the ref. flushTransactions() commits the queue early when you need the rows settled now.

Two requirements

Transactions match rows by id, so getRowId is mandatory and must derive from the data rather than the row's position — a positional id cannot survive an insert. It is also what carries row selection and expansion across updates.

The rows you pass in must be referentially stable. A new source array — a fetch response, a refresh(), or a new data prop identity — is treated as authoritative and discards applied transactions, exactly as a refresh does in any server-backed grid.

// The seed rows are held once and never replaced.
const [seedRows] = useState(() => initialOrders)

// NOT this — a new array every render throws every transaction away.
<ProGrid data={orders.slice(0, 50)} liveUpdates />

Tuning

  • batchMillis (60) — the coalescing window. Raise it to trade latency for renders.
  • flash / flashMillis (true, 900) — the cell highlight. Applied straight to the DOM rather than through React, so it costs no extra renders, and it respects prefers-reduced-motion.
  • aggMillis (250) — how often the totals row is allowed to recompute. Aggregating walks the whole filtered dataset, so under a feed it costs more than the rendering does; the totals lag by at most this much.
  • maxRows — a cap for feeds that only ever add. The far end from your addIndex is trimmed.
  • onFlush — fires after every commit with what landed.