Sub topic 12
Sorting and reversing a copy
This chapter assumes you know useState, event handlers, the spread operator, and how map, filter, and slice work. You should also know that React compares state by reference. If you pass the setter the same array, React sees no change.
Why sort and reverse need care
sort() and reverse() change the array they are called on. When that array is your state, you have mutated state directly. The mutation can happen before React is told anything. If you then pass the same array to the setter, React sees the same reference and may skip the re-render.
This looks like it should work, and it is a common bug:
function sortByName() {
// Wrong: sort() mutates items, then the same array goes back to React.
setItems(items.sort((a, b) => a.name.localeCompare(b.name)));
}The fix is to copy first, sort the copy, and store the copy.
Copy, then sort
function sortByName() {
const next = [...items];
next.sort((a, b) => a.name.localeCompare(b.name));
setItems(next);
}[...items] creates a new array. Sorting it leaves items untouched, and setItems(next) gives React a new reference to render.
Reversing works the same way:
function reverseList() {
const next = [...items];
next.reverse();
setItems(next);
}A complete example
This component runs as written in a React project.
import { useState } from 'react';
const initial = [
{ id: 1, name: 'Mango' },
{ id: 2, name: 'Apple' },
{ id: 3, name: 'Cherry' },
];
export default function FruitList() {
const [items, setItems] = useState(initial);
function sortByName() {
const next = [...items];
next.sort((a, b) => a.name.localeCompare(b.name));
setItems(next);
}
function reverseList() {
const next = [...items];
next.reverse();
setItems(next);
}
return (
<>
<button onClick={sortByName}>Sort</button>
<button onClick={reverseList}>Reverse</button>
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</>
);
}The copy is shallow
The spread creates a new array, but the objects inside are the same objects as before. Reordering them is safe. Changing one of them is not. For example, next[0].name = 'X' also changes the object inside items. To change an item, use the map pattern from the earlier chapter and copy that item.
Newer non-mutating methods
Modern JavaScript (ES2023) has toSorted() and toReversed(). They return a new array and leave the original alone.
setItems(items.toSorted((a, b) => a.name.localeCompare(b.name)));
setItems(items.toReversed());Check that your target browsers or Node version support them. Older environments need the copy-then-sort pattern, which works everywhere.
Quick reference
| Goal | Safe on state | Unsafe on state |
|---|---|---|
| Sort | `[...items].sort(fn)` or `items.toSorted(fn)` | `items.sort(fn)` |
| Reverse | `[...items].reverse()` or `items.toReversed()` | `items.reverse()` |
Exercise
A teammate writes setScores(scores.sort((a, b) => b - a)) to show scores from highest to lowest. The list sometimes fails to update on screen. What is wrong, and how do you fix it?
Show answer
sort() mutates the scores array in place and returns that same array, so the setter receives the same reference React already holds. Copy first: setScores([...scores].sort((a, b) => b - a)), or use scores.toSorted((a, b) => b - a) where it is supported.