Sub topic 12
Sorting and reversing a copy
This chapter assumes you know useState, event handlers, and the array methods map, filter, and slice. It also assumes you have read the earlier chapters on why state must not be mutated and on shallow copies. Here you apply those ideas to reordering: sorting and reversing arrays held in state.
Why reordering is a trap
sort() and reverse() look harmless, but both rearrange the array they are called on and then return that same array. Calling them on state is mutation, even though no element is added or removed.
function sortByName() {
items.sort((a, b) => a.name.localeCompare(b.name)); // mutates state
setItems(items); // same reference as before
}This code fails for two reasons:
- The array in state is changed in place, which breaks the snapshot model. Anything holding the old snapshot now sees the new order.
- The setter receives the same reference it already holds. React compares the old and new values with
Object.is, finds no difference, and may skip the re-render. The array is reordered in memory, but the screen can stay stale.
The fix follows the same rule as every other array update: make a copy, reorder the copy, and store the copy.
Sort a copy
Spread the array into a new one, then sort the new one.
function sortByName() {
const next = [...items];
next.sort((a, b) => a.name.localeCompare(b.name));
setItems(next);
}next is a new array, so mutating it does not touch state. The setter receives a new reference, so React re-renders. Reversing works the same way:
function reverseItems() {
const next = [...items];
next.reverse();
setItems(next);
}You can shorten this when you do not need the intermediate variable:
setItems([...items].reverse());
setItems([...items].sort((a, b) => a.price - b.price));The spread runs first and produces a new array. The method then mutates only that copy, which nothing else can see yet. Mutating a copy you just made is safe. The mistake is mutating an array that came from state.
A complete example
This component can be pasted into a Vite or Create React App project.
import { useState } from 'react';
const initialProducts = [
{ id: 1, name: 'Mug', price: 12 },
{ id: 2, name: 'Backpack', price: 60 },
{ id: 3, name: 'Notebook', price: 8 },
{ id: 4, name: 'Lamp', price: 35 },
];
export default function ProductList() {
const [products, setProducts] = useState(initialProducts);
function sortByName() {
const next = [...products];
next.sort((a, b) => a.name.localeCompare(b.name));
setProducts(next);
}
function sortByPrice() {
const next = [...products];
next.sort((a, b) => a.price - b.price);
setProducts(next);
}
function reverse() {
setProducts([...products].reverse());
}
return (
<>
<button onClick={sortByName}>Sort by name</button>
<button onClick={sortByPrice}>Sort by price</button>
<button onClick={reverse}>Reverse</button>
<ul>
{products.map((p) => (
<li key={p.id}>
{p.name}: ${p.price}
</li>
))}
</ul>
</>
);
}Each item has a stable id, and the list uses it as the key. When the order changes, React uses keys to move existing DOM nodes rather than rebuild them. If you keyed by array index, any local state inside the rows would stay attached to the position, not to the product.
Writing correct comparators
sort() takes a comparator function. It must return a negative number, zero, or a positive number. These mistakes are common:
| Mistake | What happens | Fix |
|---|---|---|
| No comparator on numbers: `[10, 9, 1].sort()` | Items are compared as strings, giving `[1, 10, 9]` | `sort((a, b) => a - b)` |
| Returning a boolean: `sort((a, b) => a.price > b.price)` | `true` and `false` convert to 1 and 0, and the comparator never returns a negative number. Results are unreliable | `sort((a, b) => a.price - b.price)` |
| Comparing strings with `-` | The result is `NaN` | `a.name.localeCompare(b.name)` |
| Using `<` and `>` on mixed-case text | Uppercase letters sort before lowercase | `localeCompare`, optionally with `{ sensitivity: 'base' }` |
For descending order, swap the operands: b.price - a.price. Do not sort ascending and then reverse unless you want that exact tie behavior.
sort() is stable in all current JavaScript engines. Items that compare as equal keep their relative order. You can rely on this to sort by two keys in two passes, with the less important key first. For a single pass, put the tie-breaker in the comparator:
next.sort((a, b) => a.category.localeCompare(b.category) || a.price - b.price);The non-mutating methods: toSorted and toReversed
ES2023 added toSorted(), toReversed(), toSpliced(), and with(). Each returns a new array and leaves the original alone, so no manual copy is needed.
setProducts(products.toSorted((a, b) => a.name.localeCompare(b.name)));
setProducts(products.toReversed());Check your targets before you use them. They are available in current evergreen browsers and in Node.js 20 and later. Older browsers and older Node versions throw TypeError: products.toSorted is not a function. If you support those, keep the [...array].sort() form or add a polyfill.
| Mutates the array | Returns a new array |
|---|---|
| `sort()` | `toSorted()` |
| `reverse()` | `toReversed()` |
| `splice()` | `toSpliced()` |
| `arr[i] = x` | `with(i, x)` |
The slice(), map(), filter(), and concat() methods also return new arrays.
The copy is shallow
Spread copies the array, not the objects inside it. After [...products], the new array and the old array hold references to the same product objects. Reordering is safe because you only move references around. Editing a product through the copy is not:
const next = [...products];
next.sort((a, b) => a.price - b.price);
next[0].price = 0; // Wrong: this is the same object that state holds
setProducts(next);The price change reaches the object in the previous snapshot as well. If you need to change an item while reordering, replace it with an updated copy, as in the earlier chapter on map and objects inside arrays:
const next = products.map((p) => (p.id === 3 ? { ...p, price: 0 } : p));
next.sort((a, b) => a.price - b.price);
setProducts(next);Here map already returns a new array, so you can sort it directly without another spread.
Sorting inside an updater function
When the new order depends on the latest state, for example if several updates may be queued, use an updater function. The updater must still return a new array:
// Wrong: sorts the previous state in place and returns the same reference
setProducts((prev) => prev.sort((a, b) => a.price - b.price));
// Right
setProducts((prev) => [...prev].sort((a, b) => a.price - b.price));The wrong version has an extra problem in development. In Strict Mode, React calls updater functions twice to expose impure code. A mutating updater changes the previous state during the first call, so the double call can hide or reveal bugs that are hard to trace.
Often you should not store the sorted list
Sorting is a view of the data, not a new fact. If the user picks a sort order from a dropdown, store the choice and compute the sorted list while rendering:
import { useState } from 'react';
export default function SortedList({ products }) {
const [sortKey, setSortKey] = useState('name');
const sorted = [...products].sort((a, b) =>
sortKey === 'name' ? a.name.localeCompare(b.name) : a.price - b.price
);
return (
<>
<select value={sortKey} onChange={(e) => setSortKey(e.target.value)}>
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<ul>
{sorted.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</>
);
}This way, items added or edited later appear in the right place with no extra code, and there are no two copies of the list to keep in sync. Store the sorted array in state only when the order is itself data the user controls, such as a drag-and-drop list or a "move up" button. If the list is large and sorting is slow, wrap the computation in useMemo and measure before you do.
Exercise
A component keeps scores (an array of numbers) in state. This handler is supposed to sort the scores from highest to lowest, but the list sometimes does not update, and the numbers sort incorrectly when they have different digit counts: function sortDesc() { setScores(scores.sort()); }. Rewrite it so it re-renders and sorts correctly. Then explain what is wrong with each part of the original.
Show answer
Use function sortDesc() { setScores([...scores].sort((a, b) => b - a)); }, or setScores(scores.toSorted((a, b) => b - a)) where supported. The original has three problems. First, sort() mutates the array in state. Second, it returns the same array, so setScores receives the same reference and React may skip the re-render. Third, without a comparator, sort() compares numbers as strings, so [10, 9, 1] becomes [1, 10, 9], and it only sorts ascending. The comparator (a, b) => b - a compares numerically and puts larger values first.