Skip to main content
Version: 4.xx.xxSource Code

useDataGrid

By using useDataGrid, you can get properties that are compatible with MUI X <DataGrid> component. All features such as sorting, filtering, and pagination come out of the box. Under the hood it uses useList for the fetch.

For all the other features, you can refer to the MUI X <DataGrid> documentation

💡 The useDataGrid hook is compatible with both the <DataGrid> and the <DataGridPro> components.

info

This hook is extended from useTable from the @refinedev/core package. This means that you can use all the features of useTable hook.

Basic usage

In basic usage, useDataGrid returns the data as it comes from the endpoint. By default, it reads resource from the URL.

http://localhost:3000/posts
import React from "react";
import { useDataGrid, List } from "@refinedev/mui";
import { DataGrid, GridColumns } from "@mui/x-data-grid";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
}

const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid<IPost>();

const columns = React.useMemo<GridColumns<IPost>>(
() => [
{
field: "id",
headerName: "ID",
type: "number",
width: 75,
},
{ field: "title", headerName: "Title", minWidth: 400, flex: 1 },
{
field: "status",
headerName: "Status",
width: 120,
},
],
[],
);

return (
<List>
<DataGrid {...dataGridProps} columns={columns} autoHeight />
</List>
);
};

Pagination

The hook handles pagination by setting the paginationMode, page, onPageChange, pageSize, and onPageSizeChange props that are compatible with <DataGrid>.

It also syncs the pagination state with the URL if you enable the syncWithLocation.

info

If you want to handle the pagination on client-side, you can pass the pagination.mode prop to the useDataGrid hook and set it to "client".

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid();

const {
paginationMode,
page,
onPageChange,
pageSize,
onPageSizeChange,
...restDataGridProps
} = dataGridProps;

return (
<List>
<DataGrid
columns={columns}
{...restDataGridProps}
paginationMode={paginationMode}
page={page}
onPageChange={onPageChange}
pageSize={pageSize}
onPageSizeChange={onPageSizeChange}
autoHeight
/>
</List>
);
};

Sorting

The hook handles sorting by setting the sortingMode, sortModel, and onSortModelChangeprops that are compatible with <DataGrid>.

It also syncs the sorting state with the URL if you enable the syncWithLocation.

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid();

const { sortingMode, sortModel, onSortModelChange, ...restDataGridProps } =
dataGridProps;

return (
<List>
<DataGrid
columns={columns}
{...restDataGridProps}
sortingMode={sortingMode}
sortModel={sortModel}
onSortModelChange={onSortModelChange}
autoHeight
/>
</List>
);
};

If you want to sort externally from the <DataGrid> component. You can use setSorter like this:

import { useDataGrid, List } from "@refinedev/mui";
import { Button, ButtonGroup } from "@mui/material";
import { DataGrid, GridColumns } from "@mui/x-data-grid";

const columns: GridColumns = [
{
field: "id",
headerName: "ID",
type: "number",
},
{ field: "title", headerName: "Title" },
{ field: "status", headerName: "Status" },
];

export const PostsList: React.FC = () => {
const { dataGridProps, setSorter } = useDataGrid();

const handleSorting = (order: "asc" | "desc") => {
setSorter([
{
field: "title",
order,
},
]);
};

return (
<List>
<ButtonGroup variant="outlined">
<Button onClick={() => handleSorting("asc")}>Asc</Button>
<Button onClick={() => handleSorting("desc")}>Desc</Button>
</ButtonGroup>
<DataGrid {...dataGridProps} columns={columns} autoHeight />
</List>
);
};
tip

Mui X community version only sorts the rows according to one criterion at a time. To use multi-sorting, you need to upgrade to the Pro plan.

However, multiple sorting can be done server-side without specifying the sortModel.

return <DataGrid {...dataGridProps} sortModel={undefined} autoHeight />;

When sortModel is not passed, it supports more than one criteria at a time, but cannot show which fields are sorted in <DataGrid> headers.

Filtering

The hook handles filtering by setting the filterMode, filterModel and onFilterModelChangeprops that are compatible with <DataGrid>.

It also syncs the filtering state with the URL if you enable the syncWithLocation.

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid();

const {
filterMode,
filterModel,
onFilterModelChange,
...restDataGridProps
} = dataGridProps;

return (
<List>
<DataGrid
columns={columns}
{...restDataGridProps}
filterMode={filterMode}
filterModel={filterModel}
onFilterModelChange={onFilterModelChange}
autoHeight
/>
</List>
);
};

If you want to filter externally from the <DataGrid> component. You can use setFilter like this:

import { useDataGrid, List } from "@refinedev/mui";
import { FormControlLabel, Checkbox } from "@mui/material";
import { DataGrid, GridColumns } from "@mui/x-data-grid";
const columns: GridColumns = [
{
field: "id",
headerName: "ID",
type: "number",
},
{ field: "title", headerName: "Title" },
{ field: "status", headerName: "Status" },
];

export const PostsList: React.FC = () => {
const { dataGridProps, setFilters } = useDataGrid();

const handleFilter = (
e: React.ChangeEvent<HTMLInputElement>,
checked: boolean,
) => {
setFilters([
{
field: "status",
value: checked ? "draft" : undefined,
operator: "eq",
},
]);
};

return (
<List>
<FormControlLabel
label="Filter by Draft Status"
control={<Checkbox onChange={handleFilter} />}
/>
<DataGrid {...dataGridProps} columns={columns} autoHeight />
</List>
);
};
tip

Mui X community version only filters the rows according to one criterion at a time. To use multi-filtering, you need to upgrade to the Pro plan.

However, multiple filtering can be done server-side without specifying the filterModel.

return <DataGrid {...dataGridProps} filterModel={undefined} autoHeight />;

When filterModel is not passed, it supports more than one criteria at a time, but cannot show which fields are filtered in <DataGrid> headers.

Realtime Updates

This feature is only available if you use a Live Provider.

When the useDataGrid hook is mounted, it will call the subscribe method from the liveProvider with some parameters such as channel, resource etc. It is useful when you want to subscribe to live updates.

Refer to the liveProvider documentation for more information

Properties

resource

Default: It reads the resource value from the current URL.

It will be passed to the getList method from the dataProvider as parameter via the useList hook. The parameter is usually used as an API endpoint path. It all depends on how to handle the resource in the getList method. See the creating a data provider section for an example of how resources are handled.

useDataGrid({
resource: "categories",
});

dataProviderName

If there is more than one dataProvider, you should use the dataProviderName that you will use. It is useful when you want to use a different dataProvider for a specific resource.

useDataGrid({
dataProviderName: "second-data-provider",
});

pagination.current

Default: 1

Sets the initial value of the page index.

useDataGrid({
pagination: {
current: 2,
},
});

pagination.pageSize

Default: 25

Sets the initial value of the page size.

useDataGrid({
pagination: {
pageSize: 10,
},
});

pagination.mode

Default: "server"

It can be "off", "server" or "client".

  • "off": Pagination is disabled. All records will be fetched.
  • "client": Pagination is done on the client side. All records will be fetched and then the records will be paginated on the client side.
  • "server":: Pagination is done on the server side. Records will be fetched by using the current and pageSize values.
useDataGrid({
pagination: {
mode: "client",
},
});

sorters.initial

Sets the initial value of the sorter. The initial is not permanent. It will be cleared when the user changes the sorter. If you want to set a permanent value, use the sorters.permanent prop.

Refer to the CrudSorting interface for more information

useDataGrid({
sorters: {
initial: [
{
field: "name",
order: "asc",
},
],
},
});

sorters.permanent

Sets the permanent value of the sorter. The permanent is permanent and unchangeable. It will not be cleared when the user changes the sorter. If you want to set a temporary value, use the sorters.initial prop.

Refer to the CrudSorting interface for more information

useDataGrid({
sorters: {
permanent: [
{
field: "name",
order: "asc",
},
],
},
});

sorters.mode

Default: "server"

It can be "off", or "server".

  • "off": sorters are not sent to the server. You can use the sorters value to sort the records on the client side.
  • "server":: Sorting is done on the server side. Records will be fetched by using the sorters value.
useDataGrid({
sorters: {
mode: "server",
},
});

filters.initial

Sets the initial value of the filter. The initial is not permanent. It will be cleared when the user changes the filter. If you want to set a permanent value, use the filters.permanent prop.

Refer to the CrudFilters interface for more information

useDataGrid({
filters: {
initial: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
},
});

filters.permanent

Sets the permanent value of the filter. The permanent is permanent and unchangeable. It will not be cleared when the user changes the filter. If you want to set a temporary value, use the filters.initial prop.

Refer to the CrudFilters interface for more information

useDataGrid({
filters: {
permanent: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
},
});

filters.defaultBehavior

Default: merge

The filtering behavior can be set to either "merge" or "replace".

  • When the filter behavior is set to "merge", it will merge the new filter with the existing filters. This means that if the new filter has the same column as an existing filter, the new filter will replace the existing filter for that column. If the new filter has a different column than the existing filters, it will be added to the existing filters.

  • When the filter behavior is set to "replace", it will replace all existing filters with the new filter. This means that any existing filters will be removed and only the new filter will be applied to the table.

You can also override the default value by using the second parameter of the setFilters function.

useDataGrid({
filters: {
defaultBehavior: "replace",
},
});

filters.mode

Default: "server"

It can be "off" or "server".

  • "off": filters are not sent to the server. You can use the filters value to filter the records on the client side.
  • "server":: Filters are done on the server side. Records will be fetched by using the filters value.
useDataGrid({
filters: {
mode: "off",
},
});

syncWithLocation

Default: false

When you use the syncWithLocation feature, the useDataGrid's state (e.g. sort order, filters, pagination) is automatically encoded in the query parameters of the URL, and when the URL changes, the useDataGrid state is automatically updated to match. This makes it easy to share table states across different routes or pages and allows users to bookmark or share links to specific table views.

Also, you can set this value globally on <Refine> component.

useDataGrid({
syncWithLocation: true,
});

queryOptions

useDataGrid uses useList hook to fetch data. You can pass queryOptions.

useDataGrid({
queryOptions: {
retry: 3,
},
});

meta

meta is a special property that can be used to pass additional information to data provider methods for the following purposes:

  • Customizing the data provider methods for specific use cases.
  • Generating GraphQL queries using plain JavaScript Objects (JSON).

Refer to the meta section of the General Concepts documentation for more information

In the following example, we pass the headers property in the meta object to the create method. With similar logic, you can pass any properties to specifically handle the data provider methods.

useDataGrid({
meta: {
headers: { "x-meta-data": "true" },
},
});

const myDataProvider = {
//...
getList: async ({
resource,
pagination,
sorters,
filters,
meta,
}) => {
const headers = meta?.headers ?? {};
const url = `${apiUrl}/${resource}`;

//...
//...

const { data, headers } = await httpClient.get(`${url}`, { headers });

return {
data,
};
},
//...
};

successNotification

NotificationProvider is required for this prop to work.

After data is fetched successfully, useDataGrid can call open function from NotificationProvider to show a success notification. With this prop, you can customize the success notification.

useDataGrid({
successNotification: (data, values, resource) => {
return {
message: `${data.title} Successfully fetched.`,
description: "Success with no errors",
type: "success",
};
},
});

errorNotification

NotificationProvider is required for this prop to work.

After data fetching is failed, useDataGrid will call open function from NotificationProvider to show an error notification. With this prop, you can customize the error notification.

useDataGrid({
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when getting ${data.id}`,
description: "Error",
type: "error",
};
},
});

liveMode

LiveProvider is required for this prop to work.

Determines whether to update data automatically ("auto") or not ("manual") if a related live event is received. It can be used to update and show data in Realtime throughout your app. For more information about live mode, please check Live / Realtime page.

useDataGrid({
liveMode: "auto",
});

onLiveEvent

LiveProvider is required for this prop to work.

The callback function is executed when new events from a subscription have arrived.

useDataGrid({
onLiveEvent: (event) => {
console.log(event);
},
});

liveParams

LiveProvider is required for this prop to work.

Params to pass to liveProvider's subscribe method.

initialCurrent

Deprecated

Use pagination.current instead.

Default: 1

Sets the initial value of the page index.

useDataGrid({
initialCurrent: 2,
});

initialPageSize

Deprecated

Use pagination.pageSize instead.

Default: 25

Sets the initial value of the page size.

useDataGrid({
initialPageSize: 20,
});

hasPagination

Deprecated

Use pagination.mode instead.

Default: true

Determines whether to use server-side pagination or not.

useDataGrid({
hasPagination: false,
});

initialSorter

Deprecated

Use sorters.initial instead.

Sets the initial value of the sorter. The initialSorter is not permanent. It will be cleared when the user changes the sorter. If you want to set a permanent value, use the permanentSorter prop.

Refer to the CrudSorting interface for more information

useDataGrid({
initialSorter: [
{
field: "name",
order: "asc",
},
],
});

permanentSorter

Deprecated

Use sorters.permanent instead.

Sets the permanent value of the sorter. The permanentSorter is permanent and unchangeable. It will not be cleared when the user changes the sorter. If you want to set a temporary value, use the initialSorter prop.

Refer to the CrudSorting interface for more information

useDataGrid({
permanentSorter: [
{
field: "name",
order: "asc",
},
],
});

initialFilter

Deprecated

Use filters.initial instead.

Sets the initial value of the filter. The initialFilter is not permanent. It will be cleared when the user changes the filter. If you want to set a permanent value, use the permanentFilter prop.

Refer to the CrudFilters interface for more information

useDataGrid({
initialFilter: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
});

permanentFilter

Deprecated

Use filters.permanent instead.

Sets the permanent value of the filter. The permanentFilter is permanent and unchangeable. It will not be cleared when the user changes the filter. If you want to set a temporary value, use the initialFilter prop.

Refer to the CrudFilters interface for more information

useDataGrid({
permanentFilter: [
{
field: "name",
operator: "contains",
value: "Foo",
},
],
});

defaultSetFilterBehavior

Deprecated

Use filters.defaultBehavior instead.

Default: merge

The filtering behavior can be set to either "merge" or "replace".

  • When the filter behavior is set to "merge", it will merge the new filter with the existing filters. This means that if the new filter has the same column as an existing filter, the new filter will replace the existing filter for that column. If the new filter has a different column than the existing filters, it will be added to the existing filters.

  • When the filter behavior is set to "replace", it will replace all existing filters with the new filter. This means that any existing filters will be removed and only the new filter will be applied to the table.

You can also override the default value by using the second parameter of the setFilters function.

useDataGrid({
defaultSetFilterBehavior: "replace",
});

Return Values

dataGridProps

The props needed by the <DataGrid> component.

sortingMode

Default: server

Determines whether to use server-side sorting or not.

sortModel

Current GridSortModel compatible with <DataGrid> component.

onSortModelChange

When the user sorts a column, this function is called with the new sort model.

🚨 dataGridProps.onSortModelChange automatically transform GridSortModel to CrudSorting and call setSorter function. If you want to override it, you can use like this:

<DataGrid
{...dataGridProps}
columns={columns}
autoHeight
onSortModelChange={(model, details) => {
dataGridProps.onSortModelChange(model, details);
// do something else
}}
/>

filterMode

Default: server

Determines whether to use server-side filtering or not.

filterModel

Current GridFilterModel compatible with <DataGrid> component.

onFilterModelChange

When the user filters a column, this function is called with the new filter model.

🚨 dataGridProps.onFilterModelChange automatically transform GridFilterModel to CrudFilters and call setFilters function. If you want to override it, you can use like this:

<DataGrid
{...dataGridProps}
columns={columns}
autoHeight
onFilterModelChange={(model, details) => {
dataGridProps.onFilterModelChange(model, details);
// do something else
}}
/>

onStateChange

When the user sorts or filters a column, this function is called with the new state.

🚨 The onStateChange callback is used internally by the useDataGrid hook. If you want to override it, you can use like this:

<DataGrid
{...dataGridProps}
columns={columns}
autoHeight
onStateChange={(state) => {
dataGridProps.onStateChange(state);
// do something else
}}
/>

rows

Contains the data to be displayed in the data grid. Values fetched with useList hook.

rowCount

Total number of data. Value fetched with useList hook.

loading

Indicates whether the data is being fetched.

pagination

Returns pagination configuration values(pageSize, current, setCurrent, etc.).

tableQueryResult

Returned values from useList hook.

sorters

Current sorters state.

setSorters

A function to set current sorters state.

 (sorters: CrudSorting) => void;

filters

Current filters state.

setFilters

((filters: CrudFilters, behavior?: SetFilterBehavior) => void) & ((setter: (prevFilters: CrudFilters) => CrudFilters) => void)

A function to set current filters state.

current

Current page index state. If pagination is disabled, it will be undefined.

setCurrent

React.Dispatch<React.SetStateAction<number>> | undefined;

A function to set the current page index state. If pagination is disabled, it will be undefined.

pageSize

Current page size state. If pagination is disabled, it will be undefined.

setPageSize

React.Dispatch<React.SetStateAction<number>> | undefined;

A function to set the current page size state. If pagination is disabled, it will be undefined.

pageCount

Total page count state. If pagination is disabled, it will be undefined.

createLinkForSyncWithLocation

(params: SyncWithLocationParams) => string;

A function creates accessible links for syncWithLocation. It takes SyncWithLocationParams as parameters.

sorter

Deprecated

Use sorters instead.

Current sorters state.

setSorter

Deprecated

Use setSorters instead.

A function to set current sorters state.

 (sorters: CrudSorting) => void;

FAQ

How can I handle relational data?

You can use useSelect hook to fetch relational data and filter <DataGrid> by categories.

http://localhost:3000/posts
import React from "react";
import { Option, useSelect } from "@refinedev/core";
import { useDataGrid, List } from "@refinedev/mui";
import {
DataGrid,
GridColumns,
GridValueFormatterParams,
} from "@mui/x-data-grid";

import { ICategory, IPost } from "interfaces";

const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid<IPost>({
pagination: {
current: 2,
pageSize: 10,
},
sorters: {
initial: [
{
field: "title",
order: "asc",
},
],
},
filters: {
initial: [
{
field: "status",
operator: "eq",
value: "draft",
},
],
},
syncWithLocation: true,
});

const {
options,
queryResult: { isLoading },
} = useSelect<ICategory>({
resource: "categories",
hasPagination: false,
});

const columns = React.useMemo<GridColumns<IPost>>(
() => [
{
field: "id",
headerName: "ID",
type: "number",
width: 50,
},
{ field: "title", headerName: "Title", minWidth: 400, flex: 1 },
{
field: "category.id",
headerName: "Category",
type: "singleSelect",
headerAlign: "left",
align: "left",
minWidth: 250,
flex: 0.5,
valueOptions: options,
valueFormatter: (params: GridValueFormatterParams<Option>) => {
return params.value;
},
renderCell: function render({ row }) {
if (isLoading) {
return "Loading...";
}

const category = options.find(
(item) =>
item.value.toString() ===
row.category.id.toString(),
);
return category?.label;
},
},
{
field: "status",
headerName: "Status",
minWidth: 120,
flex: 0.3,
type: "singleSelect",
valueOptions: ["draft", "published", "rejected"],
},
],
[options, isLoading],
);

return (
<List>
<DataGrid
{...dataGridProps}
columns={columns}
autoHeight
rowsPerPageOptions={[10, 20, 30, 50, 100]}
/>
</List>
);
};

How can I handle client side filtering?

You can set the filters.mode: "off" in order to disable server-side filtering. useDataGrid is fully compatible with Material UI <DataGrid> component's filtering feature.

useDataGrid({
filters: {
mode: "off",
},
});

How can I handle client side sorting?

You can set the sorting.mode: "off" in order to disable server-side sorting. useDataGrid is fully compatible with Material UI <DataGrid> component's sorting feature.

useDataGrid({
sorting: {
mode: "off",
},
});

API

Properties

Type Parameters

PropertyDesriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TSearchVariablesValues for search params{}
TDataResult data returned by the select function. Extends BaseRecord. If not specified, the value of TQueryFnData will be used as the default value.BaseRecordTQueryFnData

Return values

PropertyDescriptionType
dataGridPropsMUI X <DataGrid> propsDataGridPropsType*
tableQueryResultResult of the react-query's useQueryQueryObserverResult<{`` data: TData[];`` total: number; },`` TError>
searchIt sends the parameters it receives to its onSearch function(value: TSearchVariables) => Promise<void>
currentCurrent page index state (returns undefined if pagination is disabled)number | undefined
totalPageTotal page count (returns undefined if pagination is disabled)number | undefined
setCurrentA function that changes the current (returns undefined if pagination is disabled)React.Dispatch<React.SetStateAction<number>> | undefined
pageSizeCurrent pageSize state (returns undefined if pagination is disabled)number | undefined
setPageSizeA function that changes the pageSize (returns undefined if pagination is disabled)React.Dispatch<React.SetStateAction<number>> | undefined
hideFooterPaginationWhether to hide the footer pagination accordingly your pagination.mode and hasPagination propsboolean
sortersCurrent sorting stateCrudSorting
setSortersA function that accepts a new sorters state(sorters: CrudSorting) => void
sorterCurrent sorting stateCrudSorting
setSorterA function that accepts a new sorters state(sorters: CrudSorting) => void
filtersCurrent filters stateCrudFilters
setFiltersA function that accepts a new filter state(filters: CrudFilters) => void
createLinkForSyncWithLocationA function create accessible links for syncWithLocation(params: SyncWithLocationParams) => string;

DataGridProps

PropertyDefaultPropertyDefault
rows[]pageSize25
rowCount0onPageSizeChange
disableSelectionOnClicktruesortingMode"server"
loadingfalsesortModel
paginationMode"server"onSortModelChange
page0filterMode"server"
onPageChangefilterModel
onStateChangeonFilterModelChange

Example

RUN IN YOUR LOCAL
npm create refine-app@latest -- --example table-material-ui-use-data-grid