Blog>
Snippets

Initializing the useTable Hook

Shows how to initialize the React TanStack Table library's useTable hook with basic configurations, preparing a table structure.
import { useTable } from 'react-table';
Imports the useTable hook from the react-table package.
const data = React.useMemo(() => [{ name: 'John Doe', age: 30 }, { name: 'Jane Doe', age: 25 }], []);
Defines the data for the table. useMemo is used to optimize performance by memoizing the data.
const columns = React.useMemo(() => [
    { Header: 'Name', accessor: 'name' },
    { Header: 'Age', accessor: 'age' }
], []);
Defines the columns for the table. Each column is defined by an object specifying the header text and the accessor key that matches the data keys.
const tableInstance = useTable({ columns, data });
Initializes the useTable hook with the defined columns and data, creating a table instance.
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance;
Destructures necessary properties and functions from the table instance for rendering the table.