0

I can't memoized my Material UI Datagridtable in React


const Mockdata = [{id: 1 , user: "john",School: "LAL" },
{id: 2 , user: "Ruby",School: "LAL" }]



const column = [
  { field: "user", headerName: "Username", width: 250 },
  { field: "School", headerName: "School", width: 250 },
];

const Row = Mockdata.map((data) => ({
    id: data.id,
    user: data.user,
    School: data.School,
}))

const MemoizedRow = React.memo(Row)
const MemoizedColumn = React.memo(column)

<DataGrid
  rows={MemoizedRow}
  columns={MemoizedColumn}
  initialState={{
    pagination: {
      paginationModel: {
        pageSize: 15,
      },
    },
  }}
  pageSizeOptions={[15]}
/>;

warrning: memo: The first argument must be a component. Instead received: object

warrning: Failed prop type: Invalid prop `rows` of type `object` supplied to `ForwardRef(DataGrid)`, expected an array.

Is there a way to overcome this error or warning ?

Olivier Tassinari
  • 8,238
  • 4
  • 23
  • 23

1 Answers1

0

That is because you are using React.memo, which is a wrapper on react components. Since you are using objects, what you are looking for is actually the useMemo hook, which is used to memoize any data, usually the result of an expensive calculation that you want to minimize.

In your example, you should use something like:

const columns = useMemo(() => [
  { field: "user", headerName: "Username", width: 250 },
  { field: "School", headerName: "School", width: 250 },
], []);

const rows = useMemo(() => mockData.map((data) => ({
    id: data.id,
    user: data.user,
    School: data.School,
})), [mockData]);

Since your columns are static and unchanging, note that the second argument should be an empty dependency array, whereas for the rows, since they are dependant on external data (Even though for this specific example your MockData is static, so you can omit the items in the dependency array - but if that data had originated elsewhere, this is how you'd use the dependency array of useMemo)

Tom V.
  • 1
  • 1
  • 2