Skip to content

Sortable Data Table

Medium ~30 min

What you'll build

A data table displaying a list of users with columns for name, age, and role. Clicking a column header sorts the table by that column, with toggle between ascending and descending.

Goals

  • Render tabular data with .map()
  • Implement column sorting logic
  • Use useMemo to cache the sorted data
  • Handle sort direction toggling

Prerequisites

  • List rendering with map
  • useState and useMemo
  • Array sort method

Steps

  1. 1

    Set up data and sort state

    Create an array of user objects and state for the sort column and direction.

    Code
    const [sortKey, setSortKey] = useState("name");
    const [sortDir, setSortDir] = useState("asc");
    
    const users = [
      { name: "Alice", age: 30, role: "Admin" },
      { name: "Bob", age: 25, role: "User" },
      { name: "Charlie", age: 35, role: "Editor" },
    ];

    Expected result

    Data and sort state are ready.

  2. 2

    Memoize the sorted data

    Use useMemo to sort the users array based on sortKey and sortDir. This avoids re-sorting on every render.

    Code
    const sortedUsers = useMemo(() => {
      return [...users].sort((a, b) => {
        const val = a[sortKey] < b[sortKey] ? -1 : a[sortKey] > b[sortKey] ? 1 : 0;
        return sortDir === "asc" ? val : -val;
      });
    }, [users, sortKey, sortDir]);

    Expected result

    Data is sorted and cached. Changing sort state re-sorts.

  3. 3

    Render the table with sortable headers

    Render a table with clickable headers that update sortKey and toggle sortDir.

    Code
    <table>
      <thead>
        <tr>
          <th onClick={() => handleSort("name")}>Name</th>
          <th onClick={() => handleSort("age")}>Age</th>
          <th onClick={() => handleSort("role")}>Role</th>
        </tr>
      </thead>
      <tbody>
        {sortedUsers.map(u => (
          <tr key={u.name}>
            <td>{u.name}</td><td>{u.age}</td><td>{u.role}</td>
          </tr>
        ))}
      </tbody>
    </table>

    Expected result

    Clicking a header sorts the table by that column.

  4. 4

    Add state management & event handling

    Use useState to manage component state and add onClick/onChange handlers to interactive elements. State is the heart of React components, and event handling lets them respond to user actions.

    Code
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    Expected result

    Clicking the button increments the count; the input content updates in real time as you type.

  5. 5

    Add Props validation & component split

    Define a Props interface (TypeScript) or propTypes for the component, and split large components into smaller sub-components. Type-safe Props make the component interface clear and reusable.

    Code
    interface ChildProps {
      label: string;
      value: number;
      onChange: (v: number) => void;
    }
    
    function Child({ label, value, onChange }: ChildProps) {
      return (
        <label>
          {label}
          <input
            type="number"
            value={value}
            onChange={(e) => onChange(Number(e.target.value))}
          />
        </label>
      );
    }

    Expected result

    The child component receives type-safe Props; the parent can reuse it to render multiple fields.

Try it yourself

What you learned

You learned to render tabular data, implement sorting with useMemo for performance, and handle user interactions on table headers. This is a common pattern in admin dashboards and data-heavy apps.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic