Instead of utilizing useState
, consider using useRef
. Unlike useState
, useRef
does not trigger a re-render of the component as it operates independently from the component lifecycle, thus resolving the issue at hand.
You can manipulate and retrieve the selected rows through useRef.current
.
I have made modifications to your sample component by implementing useRef
instead of useState
below and provided a functional demo. Please note that in the example, the selected rows are displayed in the console log.
import React from "react";
import "./styles.css";
import { ColDef, DataGrid, RowsProp } from "@material-ui/data-grid";
export default function App() {
const selectedRows = React.useRef([]);
const onSelect = (event) => {
selectedRows.current = event.rows;
console.log(selectedRows.current);
};
const rows: RowsProp = [
{
id: 0,
name: "LuluBox_v4.8.8_apkpure.com.apk",
type: "application/vnd.android.package-archive",
lastModifiedDate: "2020-10-20T00:27:43.669Z",
size: "13805 kB",
file: { path: "LuluBox_v4.8.8_apkpure.com.apk" }
},
{
id: 1,
name: "LuluBox_v4.8.8_apkpure.com.apk",
type: "application/vnd.android.package-archive",
lastModifiedDate: "2020-10-20T00:27:43.669Z",
size: "13805 kB",
file: { path: "LuluBox_v4.8.8_apkpure.com.apk" }
}
];
const columns: ColDef[] = [
{ field: "id", hide: true },
{ field: "name", headerName: "Name", width: 400 },
{ field: "size", headerName: "Size", width: 250 },
{ field: "lastModifiedDate", headerName: "lastModifiedDate", width: 400 }
];
return (
<DataGrid
rows={rows}
columns={columns}
pageSize={8}
autoHeight
checkboxSelection
hideFooter
onSelectionChange={onSelect}
/>
);
}