Array updates that preserve previous state
Use a small immutable transformation and assertions to keep a sorted view from mutating shared state.
A component may show one collection in several views: the original order, open work and a list sorted by priority. If a view sorts the shared array in place, the act of displaying it can also change the source order.
React's state guidance treats arrays in state as read-only. A practical way to follow that guidance is to put the transformation in a small function that accepts an array and returns the view. The function can be checked independently of rendering.
A complete example
Save this block as example.mjs and run node example.mjs. It needs no packages.
import assert from "node:assert/strict";
function openByPriority(rows) {
const rank = { high: 0, medium: 1, low: 2 };
return rows
.filter(row => !row.done)
.sort((a, b) => rank[a.priority] - rank[b.priority]);
}
function toggle(rows, id) {
return rows.map(row =>
row.id === id ? { ...row, done: !row.done } : row
);
}
const original = [
{ id: "low", priority: "low", done: false },
{ id: "high", priority: "high", done: false }
];
assert.deepEqual(openByPriority(original).map(row => row.id), ["high", "low"]);
assert.deepEqual(original.map(row => row.id), ["low", "high"]);
const changed = toggle(original, "low");
assert.equal(changed[0].done, true);
assert.equal(original[0].done, false);
assert.deepEqual(openByPriority([]), []);
console.log("array example passed");
Here filter supplies a fresh array before sort runs. The sort can reorder that result without reordering original. The toggle operation also creates a replacement object for the matching row; it does not merely copy the array and then mutate a shared object.
Connect the function to state
A component can derive its visible rows from current state. An event that changes completion can pass the transformation to a functional state update, such as setRows(current => toggle(current, id)). Keep identifiers stable so one action selects one logical record.
Do not mutate a row through the derived list. The unchanged rows still refer to the same objects. Sharing those objects is useful when the transformation only changes order or membership, but it does not make nested values immutable.
Verify the contract
The returned order is only half the assertion. Keeping the original order unchanged catches an accidental replacement of the copy with an in-place sort. Empty input catches assumptions that the first row always exists. Equal-priority rows need a separately stated tie rule if their order matters to the product.
This example does not establish rendering speed or justify memoizing every list. It checks the transformation's behavior. Measure a real rendering problem before adding another cache.
References: React: updating arrays in state, Array.sort.