Blog>
Snippets

Initializing a Basic Table with useTable Hook

Show how to set up a basic table using the useTable hook, including defining columns and initial table state.
import React from 'react';
import { useTable } from 'react-table';
Import React along with the useTable hook from react-table.
const data = React.useMemo(
  () => [
    { col1: 'Hello', col2: 'World' },
    { col1: 'react-table', col2: 'rocks' },
    { col1: 'whatever', col2: 'you want' },
  ],
  []
);
Define the data for the table using useMemo for optimized performance. This example includes a simple array of objects.
const columns = React.useMemo(
  () => [
    {
      Header: 'Column 1',
      accessor: 'col1', // accessor is the 'key' in the data
    },
    {
      Header: 'Column 2',
      accessor: 'col2',
    },
  ],
  []
);
Define the columns for the table, including headers and accessors which match keys in the data object.
const {
  getTableProps,
  getTableBodyProps,
  headerGroups,
  rows,
  prepareRow,
} = useTable({ columns, data });
Initialize the useTable hook with the columns and data. This provides methods and properties needed to build the table structure.
return (
  <table {...getTableProps()}>
    <thead>
      {headerGroups.map(headerGroup => (
        <tr {...headerGroup.getHeaderGroupProps()}>
          {headerGroup.headers.map(column => (
            <th {...column.getHeaderProps()}>{column.render('Header')}</th>
          ))}
        </tr>
      ))}
    </thead>
    <tbody {...getTableBodyProps()}>
      {rows.map(row => {
        prepareRow(row);
        return (
          <tr {...row.getRowProps()}>
            {row.cells.map(cell => {
              return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
            })}
          </tr>
        );
      })}
    </tbody>
  </table>
);
Render the table structure using JSX, dynamically creating the table headers and rows based on the provided data and columns.