Blog>
Snippets

Setting Up a Basic TanStack Table

Showcase the initial steps to set up a basic TanStack Table with columns and data. Include how to define columns and pass data using the useTable hook.
import { useTable } from '@tanstack/react-table';
import React from 'react';
First, import useTable from TanStack Table and React to use hooks.
const data = React.useMemo(() => [{ id: 1, name: 'John', age: 28 }, { id: 2, name: 'Jane', age: 34 }], []);
Define the data array using useMemo for performance optimization. This data will be displayed in the table.
const columns = React.useMemo(() => [
    { accessorKey: 'id', header: 'ID' },
    { accessorKey: 'name', header: 'Name' },
    { accessorKey: 'age', header: 'Age' }
], []);
Define the columns array using useMemo. Each column requires an accessorKey which corresponds to the keys in your data array and a header which is the name displayed in the table header.
function Table() {
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({ columns, data });

    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>
    );
}
Create the Table component. It uses destructuring to extract table methods and arrays from useTable. Render the table using HTML <table>, <thead>, and <tbody> elements, mapping over headerGroups for table headers and over rows for table data.