sort() mutates and is ignored; toSorted() works
sort() reordered the state array secretly, but the screen still showed the old order. The next real update (reverse) then revealed the hidden change: the reverse is of the sorted array.
Arrays in state are read-only too: add, remove, replace, insert, reorder and sort by building a new array with spread, filter, map, slice or the copying methods toSorted and toReversed, and copy any object inside an array before changing it.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
State todos is [{ id, text, done }]. Write the three handlers addTodo(text), toggleTodo(id) and deleteTodo(id) without mutating.
Write a handler that moves the item with a given id one place up in the list (do nothing if it's already first).
Explain it without notes
Which array methods should you avoid on state, and what do you use instead?
How do you insert an item at position i without mutating?
Why can [...list] followed by copy[0].done = true still be a mutation bug?
Why should list items be identified by id instead of index?
Preview
Console
Nothing logged yet.Expected console output
render: [ 42, 7, 99, 15 ]
after sort(), the array is [ 7, 15, 42, 99 ] but no render happened
screen shows: 42 · 7 · 99 · 15
render: [ 99, 42, 15, 7 ]