How to sort a list in React

Implementing sorting functionality allows users to organize data in React lists by any column, essential for data tables and organized content. As the creator of CoreUI with over 11 years of React development experience since 2014, I’ve built sortable lists and tables in countless enterprise applications. The most effective solution is to track the sort field and direction in state and use the array sort method to reorder data. This approach provides flexible, client-side sorting with clear visual feedback.

Use state to track sort field and direction for list sorting in React.

const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' })

const data = [
  { id: 1, name: 'John Doe', age: 30, salary: 50000 },
  { id: 2, name: 'Jane Smith', age: 25, salary: 60000 },
  { id: 3, name: 'Bob Johnson', age: 35, salary: 55000 }
]

const sortedData = [...data].sort((a, b) => {
  if (!sortConfig.key) return 0

  const aValue = a[sortConfig.key]
  const bValue = b[sortConfig.key]

  if (aValue < bValue) {
    return sortConfig.direction === 'asc' ? -1 : 1
  }
  if (aValue > bValue) {
    return sortConfig.direction === 'asc' ? 1 : -1
  }
  return 0
})

const handleSort = (key) => {
  setSortConfig({
    key,
    direction: sortConfig.key === key && sortConfig.direction === 'asc' ? 'desc' : 'asc'
  })
}

return (
  <table>
    <thead>
      <tr>
        <th onClick={() => handleSort('name')}>Name</th>
        <th onClick={() => handleSort('age')}>Age</th>
        <th onClick={() => handleSort('salary')}>Salary</th>
      </tr>
    </thead>
    <tbody>
      {sortedData.map(item => (
        <tr key={item.id}>
          <td>{item.name}</td>
          <td>{item.age}</td>
          <td>{item.salary}</td>
        </tr>
      ))}
    </tbody>
  </table>
)

The sortConfig state tracks which field to sort by and the direction (ascending or descending). The spread operator creates a copy of the array before sorting to avoid mutating the original data. The sort comparison function uses the configured key and direction to order items. Clicking a header toggles between ascending and descending order for that column.

Best Practice Note

This is the same sorting implementation we use in CoreUI React tables for data organization. For better UX, add visual indicators (arrows) to show the current sort column and direction. For large datasets, consider server-side sorting to improve performance and reduce client-side processing.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author