Sub topic 7
Which array methods mutate and which do not
This chapter assumes you know JavaScript arrays, the spread operator, map, filter, and slice. It also assumes you can write a React function component with useState and handle events. You should already know that React state is a snapshot and that you replace state instead of editing it. Here you learn which array methods change an array in place and which return a new one, so you can pick the right method for each state update.
Why the distinction matters
When state holds an array, calling a method on it can change that same array in memory. React compares the old and new state by reference. If you mutate the array and then pass it to the setter, the reference has not changed. React may skip the re-render, and the snapshot that earlier renders captured has been silently altered.
A mutating method changes the array it is called on. A non-mutating method leaves the original alone and returns a new array or a plain value. In state updates you want the second kind. When you need a mutating method, you first make a copy and apply it to the copy.
The reference table
| Task | Avoid (mutates) | Prefer (returns a new array) |
|---|---|---|
| Add | `push`, `unshift` | `[...arr, item]`, `[item, ...arr]`, `concat` |
| Remove | `pop`, `shift`, `splice` | `filter`, `slice` |
| Replace | `splice`, `arr[i] = x` | `map` |
| Sort or reverse | `sort`, `reverse` | Copy first, then `sort` or `reverse` the copy |
| Fill or copy within | `fill`, `copyWithin` | `map`, or copy first |
Some methods do not fit either column because they return values and change nothing, such as indexOf, includes, find, some, every, join, and reduce. You can use these freely on state.
Mutating methods in practice
The following component shows the failure. It pushes onto the state array and passes the same array back.
import { useState } from 'react';
export default function BrokenList() {
const [names, setNames] = useState(['Ada', 'Grace']);
function addName() {
names.push('Linus'); // mutates the array held in state
setNames(names); // same reference, so React sees no change
}
return (
<div>
<button onClick={addName}>Add</button>
<ul>
{names.map((n, i) => (
<li key={i}>{n}</li>
))}
</ul>
</div>
);
}Clicking the button changes the array, but nothing on screen updates, because setNames received the reference it already had. The array is also now wrong in every closure that captured it.
The fixed version builds a new array.
import { useState } from 'react';
export default function FixedList() {
const [names, setNames] = useState(['Ada', 'Grace']);
function addName() {
setNames([...names, 'Linus']);
}
return (
<div>
<button onClick={addName}>Add</button>
<ul>
{names.map((n) => (
<li key={n}>{n}</li>
))}
</ul>
</div>
);
}The confusing case: `slice` and `splice`
slice and splice have nearly identical names and opposite behavior.
slice(start, end)copies a portion of the array and returns it. The original is unchanged. It is safe.splice(start, deleteCount, ...items)removes and inserts items in the original array and returns the removed items. It mutates.
const letters = ['a', 'b', 'c', 'd'];
const copy = letters.slice(1, 3);
console.log(copy); // ['b', 'c']
console.log(letters); // ['a', 'b', 'c', 'd'] (unchanged)
const removed = letters.splice(1, 2);
console.log(removed); // ['b', 'c']
console.log(letters); // ['a', 'd'] (changed in place)A common mistake is reading splice's return value as the new array. It returns the removed items, so assigning it to state would replace your list with the wrong data.
Sorting and reversing
sort and reverse mutate the array and also return it. That return value is the same reference, so setItems(items.sort()) still passes the original array back. Copy first.
function sortByName() {
const next = [...items];
next.sort((a, b) => a.name.localeCompare(b.name));
setItems(next);
}Newer JavaScript runtimes also provide toSorted, toReversed, toSpliced, and with. These return a modified copy and leave the original alone.
const sorted = items.toSorted((a, b) => a.name.localeCompare(b.name));
const withoutSecond = items.toSpliced(1, 1);
const replaced = items.with(0, { id: 1, name: 'Replaced' });Check your target environments before you rely on them. They arrived in browsers and Node.js around 2023, so older runtimes lack them. If you need to support those, use the copy-then-mutate pattern.
Assignment by index also mutates
Assigning to an index is a mutation too, even though it is not a method call.
items[0] = { id: 1, name: 'Changed' }; // mutates stateUse map to produce a new array with the one element replaced.
setItems(items.map((item, i) => (i === 0 ? { id: 1, name: 'Changed' } : item)));The same applies to assigning items.length = 0, which empties the array in place. Pass [] to the setter instead.
A copy is shallow
Making a copy of the array does not copy the objects inside it. [...items] creates a new array, but each element is the same object as before. That has a consequence for the method choice.
const next = [...items];
next[0].done = true; // still mutates the object that is in state
setItems(next);The array reference is new, so React re-renders. But the object at index 0 was changed in place, and any earlier snapshot sees the change. Copying protects the array, not the objects in it. To change an item, make a new item with spread, as the later chapter on objects inside arrays covers in full.
setItems(items.map((item, i) => (i === 0 ? { ...item, done: true } : item)));How the pieces connect
The diagram shows the decision you make for each array update.
Is mutating a local copy allowed?
Mutating is fine when the array is brand new and not yet shared. This is safe.
function addSorted(title) {
const next = [...todos, { id: nextId++, title, done: false }];
next.sort((a, b) => a.title.localeCompare(b.title));
setTodos(next);
}next was created inside the function and nothing else holds it. Calling sort on it changes only your own copy. The rule is not "never call push". The rule is "never change an array or object that React already holds in state".
Common errors
- Passing the result of
sort()orreverse()on the state array to the setter. The reference is unchanged, so the update may not render. - Using the return value of
spliceorpushas the new array.splicereturns removed items andpushreturns the new length. - Calling
[...items].sort()on objects without a comparator. The default sort converts items to strings, so objects all become[object Object]. - Copying the array and then mutating an object inside it.
- Using
toSortedortoSplicedin an environment that does not support them, which throws aTypeErrorat runtime.
Exercise
A component keeps const [items, setItems] = useState([...]) and has a handler function reverseList() { setItems(items.reverse()); }. The list does not update reliably. Explain why, and rewrite the handler.
Show answer
reverse mutates the array in place and returns that same array, so setItems receives the same reference that is already in state. React cannot tell the value changed, and the mutation has also altered the array that earlier renders captured. Copy first and reverse the copy: function reverseList() { const next = [...items]; next.reverse(); setItems(next); }. In environments that support it, setItems(items.toReversed()) does the same in one step.
Exercise
Sort each of these as mutating or non-mutating: slice, splice, concat, pop, filter, sort, find, unshift. Then name the non-mutating method you would use to remove the item with id === 3 from state.
Show answer
Mutating: splice, pop, sort, unshift. Non-mutating: slice, concat, filter, find. To remove the item with id === 3, use setItems(items.filter((item) => item.id !== 3)).
Exercise
This handler marks the first todo as done, but it still has a bug: const next = [...todos]; next[0].done = true; setTodos(next);. What is wrong, and how do you fix it?
Show answer
The spread creates a new array, but next[0] is the same object that is in state, so next[0].done = true mutates state. Replace the item with a copy: setTodos(todos.map((t, i) => (i === 0 ? { ...t, done: true } : t)));.