Skip to content
Advertisement

Why use `useTable` over `ReactTable` when using react-table

On their npm page, the example shows the usage of <ReactTable> component:

import ReactTable from 'react-table'
...
render() {
  return (
    <ReactTable
      data={data}
      columns={columns}
    />
  )
}

However, on their API Docs and examples, they all use useTable.

import { useTable } from 'react-table';

function Table({ columns, data }) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({
    columns,
    data,
  })

  // Render the UI for your table
  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, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => {
                  return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                })}
              </tr>
            )}
        )}
      </tbody>
    </table>
  )
}

...

render () {
  return (
    <Table columns={columns} data={data} />
  )
}

So, my question is: Why would someone use hooks(useTable, useFilters, and etc…) and make Table component when he/she can just use a that’s already provided. I’m pretty sure they didn’t forget updating their npm page’s example… or did they?

Advertisement

Answer

react-table v7 is a “headless” UI library which means that it provides only the backend table functionality, and it requires you to implement the rendering of the table with your own React components.

This means that you can apply the backend table code to whichever style of table you want (e.g. Bootstrap, Material UI, vanilla HTML etc.) and you get precise control of where to hook-up this library to the UI.

Most table libraries (including react-table pre v7!) have predefined functionality and behaviours which might not be suitable for you in certain cases; however when using react-table v7 you would be able to cater for these situations by implementing your own UI code and then hooking it up to your react-table hook code.

Advertisement