# Performance
Package: @mantine/data-grid
Import: import { Performance } from '@mantine/data-grid';
Description: DataGrid rendering model, stable options, large data sets

## How rows render

Body rows are memoized. A row re-renders only when its own data, selection, expansion
or editing state changes. Changes that concern every row re-render all of them: a new
`columns` array, column visibility, order and sizes, grouping and size changes.

The browser adds its own cost on top of React. A `<table>` is laid out as a whole, so any
change in one cell makes the browser re-layout all rows that are in the DOM. Virtualized rows
are independent blocks and do not pay this cost. The number of rows in the DOM is what
every interaction costs, keep it small.

## Rows in the DOM

* Up to about a thousand rows render fine without extra setup.
* Above that, paginate with `pageSize` or set `virtualize="rows"` with `height`.
  Row selection, expansion, editing and grouping work the same way in both modes,
  see [Virtualization](https://alpha.mantine.dev/llms/data-grid-virtualization.md) for the exceptions.
* Grids with 50 or more columns need `virtualize="columns"` or `virtualize="rows,columns"`.
* [Tree data](https://alpha.mantine.dev/llms/data-grid-tree-data.md) with thousands of expanded rows needs row virtualization
  as well, the row count that matters is the number of visible rows.

```tsx
<DataGrid store={store} virtualize="rows" height={600} />
```

## Stable options

`useDataGrid` options and `DataGrid` props are compared by identity. A value created during
render is new on every render, and the grid treats it as a change. Define these values outside
the component or wrap them in `useMemo`/`useCallback`:

* `data` – a new array rebuilds the row model and re-renders every row, it also resets the page
  index, expanded rows and cell selection
* `columns` – a new array remounts every cell
* `enableRowSelection`, `enableMultiRowSelection`, `getRowCanExpand`, `getCellStatus`
  and `getRowHeight` functions
* `labels`, `classNames`, `styles` and `attributes` objects

Event handlers such as `onRowClick`, `onEditSave` and `renderExpandedRow` can be inline,
rows always call the latest version without re-rendering.

```tsx
import { useMemo, useState } from 'react';
import { DataGrid, DataGridColumnDef, DataGridRow, useDataGrid } from '@mantine/data-grid';

// ✅ Defined once
const columns: DataGridColumnDef<User>[] = [
  { accessorKey: 'name', header: 'Name', enableSorting: true },
  { accessorKey: 'email', header: 'Email' },
];

const canSelect = (row: DataGridRow<User>) => row.original.status !== 'archived';

function Demo({ users }: { users: User[] }) {
  const [showArchived, setShowArchived] = useState(false);

  // ✅ Derived data is memoized
  const data = useMemo(
    () => (showArchived ? users : users.filter((user) => user.status !== 'archived')),
    [users, showArchived]
  );

  const store = useDataGrid({
    data,
    columns,
    getRowId: (row) => row.id,
    enableRowSelection: canSelect,
  });

  // ❌ Every render passes new values: all rows re-render on every state change
  // const store = useDataGrid({
  //   data: users.filter((user) => user.status !== 'archived'),
  //   columns: [{ accessorKey: 'name', header: 'Name' }],
  //   enableRowSelection: (row) => row.original.status !== 'archived',
  // });

  return <DataGrid store={store} />;
}
```

## Cell renderers

A `cell` function runs every time its row renders. Keep it cheap: create `Intl` formatters
and lookup tables at module level, and prefer plain text or a `Badge` over a component with
its own state. A row action menu is fine, its dropdown is not rendered until it opens.

Values that cells read from your own React context must be memoized too. A context value
created on every render re-renders every cell that reads it:

```tsx
const value = useMemo(() => ({ onEdit, onDelete }), [onEdit, onDelete]);
```

## Sorting and filtering large data sets

Client-side sorting and filtering go through every row. With a hundred thousand rows, each sort
or each search keystroke takes a noticeable fraction of a second, while the grid renders
only the rows on screen. Debounce the search input and pass the debounced value to the
store, the input itself stays responsive:

```tsx
import { useState } from 'react';
import { TextInput } from '@mantine/core';
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { useDebouncedValue } from '@mantine/hooks';

function Demo() {
  const [search, setSearch] = useState('');
  const [debouncedSearch] = useDebouncedValue(search, 200);

  const store = useDataGrid({
    data,
    columns,
    getRowId: (row) => row.id,
    globalFilter: debouncedSearch,
    onGlobalFilterChange: (value) => setSearch(String(value ?? '')),
  });

  return (
    <DataGrid store={store} virtualize="rows" height={600}>
      <DataGrid.Toolbar>
        <TextInput
          size={store.getControlSize()}
          placeholder="Search"
          value={search}
          onChange={(event) => setSearch(event.currentTarget.value)}
        />
      </DataGrid.Toolbar>
    </DataGrid>
  );
}
```

Above a few hundred thousand rows, or when the data does not fit in memory, move sorting,
filtering and pagination to the API, see [Server-side](https://alpha.mantine.dev/llms/data-grid-server-side.md).

## Finding the cause of slow renders

Use the React DevTools profiler with "Record why each component rendered" enabled. When
every body cell renders after an unrelated state change, one of the options listed in
[Stable options](#stable-options) is created during render. When only a few cells render but the
interaction is still slow, the cost is in the browser layout, reduce the number of rows in the DOM.
