0
0
ReactHow-ToBeginner · 3 min read

How to Sort List in React: Simple Guide with Examples

To sort a list in React, use the JavaScript Array.prototype.sort() method on a copy of your list and update the state with the sorted array. Always avoid mutating the original state directly by creating a new sorted array before setting state.
📐

Syntax

Use array.slice() to copy the list, then array.sort() with a compare function to sort. Finally, update React state with the sorted array.

  • array.slice(): creates a shallow copy to avoid changing original data.
  • array.sort((a, b) => a - b): sorts numbers in ascending order.
  • setList(sortedArray): updates the component state to re-render with sorted list.
javascript
const sortedArray = array.slice().sort((a, b) => a - b);
setList(sortedArray);
💻

Example

This example shows a React functional component that sorts a list of numbers when a button is clicked. It uses useState to hold the list and updates it with a sorted copy.

javascript
import React, { useState } from 'react';

export default function SortList() {
  const [list, setList] = useState([5, 3, 8, 1, 2]);

  const sortList = () => {
    const sorted = list.slice().sort((a, b) => a - b);
    setList(sorted);
  };

  return (
    <div>
      <h3>Numbers:</h3>
      <ul>
        {list.map((num, index) => (
          <li key={index}>{num}</li>
        ))}
      </ul>
      <button onClick={sortList}>Sort Ascending</button>
    </div>
  );
}
Output
Numbers: 5 3 8 1 2 [Sort Ascending button]
⚠️

Common Pitfalls

Common mistakes include mutating the original list directly, which can cause React not to re-render because state is mutated in place. Always create a new array copy before sorting.

Also, sort() without a compare function sorts items as strings, which can lead to unexpected order for numbers.

javascript
/* Wrong: mutates original state */
list.sort((a, b) => a - b);
setList(list);

/* Right: copy before sorting */
const sorted = list.slice().sort((a, b) => a - b);
setList(sorted);
📊

Quick Reference

  • Use slice() to copy arrays before sorting.
  • Always provide a compare function to sort() for numbers.
  • Update React state with the new sorted array to trigger re-render.
  • Sorting strings can use localeCompare() for proper alphabetical order.

Key Takeaways

Always copy the list before sorting to avoid mutating React state directly.
Use a compare function in sort() to get correct numeric or custom order.
Update state with the sorted array to trigger React to re-render the list.
Avoid sorting the original array directly to prevent bugs and stale UI.
For strings, use localeCompare() inside sort() for accurate alphabetical sorting.