Sub topic 11
Inserting at a specific position
This chapter assumes you know JavaScript arrays, slice, the spread operator, and the useState hook. You should also be comfortable with React event handlers. By the end, you will be able to insert an item at any index of an array held in state without mutating it. You will also be able to spot the common mistakes that come with index-based inserts.
Why insertion needs its own pattern
Earlier chapters showed three array operations. Spread at the end adds an item, filter removes one, and map replaces one. None of them puts a new item in the middle.
The obvious tool is splice. It inserts items at an index, but it mutates the array it is called on. If you call it on the array in state, you change the current snapshot in place. React then receives the same reference from the setter and may skip the render.
// Wrong: splice changes the array that state already holds.
items.splice(1, 0, newItem);
setItems(items);The fix follows the same rule as every other update. Build a new array and pass that to the setter.
The slice and spread pattern
slice(start, end) returns a new array with the items from start up to, but not including, end. It never changes the original. If you omit end, it copies through to the last item.
To insert at an index, take everything before the index, then the new item, then everything from the index onward.
const index = 1;
const newItem = { id: 99, title: 'Inserted' };
const next = [
...items.slice(0, index),
newItem,
...items.slice(index),
];
setItems(next);If items holds items A, B and C, then index = 1 gives [A, newItem, B, C]. The item that used to sit at index 1 moves to index 2, and everything after it shifts one place along.
The new item lands at position index in the result. That is the same meaning splice(index, 0, newItem) has, so you can translate between the two directly.
A complete component
Here is a runnable component. It inserts a new item after the one the user chooses. The insert position is index + 1.
import { useState } from 'react';
let nextId = 3;
export default function InsertList() {
const [items, setItems] = useState([
{ id: 0, name: 'Apple' },
{ id: 1, name: 'Banana' },
{ id: 2, name: 'Cherry' },
]);
function insertAfter(index) {
const newItem = { id: nextId++, name: 'New fruit ' + nextId };
setItems([
...items.slice(0, index + 1),
newItem,
...items.slice(index + 1),
]);
}
return (
<ul>
{items.map((item, index) => (
<li key={item.id}>
{item.name}{' '}
<button onClick={() => insertAfter(index)}>Insert after</button>
</li>
))}
</ul>
);
}Two details matter here. The key is item.id, not the index. The id for the new item comes from a counter outside the component, so it stays unique across renders.
Edge cases
Index values at the edges of the array behave well, but you should know what each one does.
| Index | Result of the slice and spread pattern |
|---|---|
| `0` | The new item goes first. `slice(0, 0)` is empty, and `slice(0)` is the whole array. |
| `items.length` | The new item goes last. `slice(0, length)` is the whole array, and `slice(length)` is empty. |
| Greater than `items.length` | `slice` clamps to the array length, so the new item goes last. |
| Negative, such as `-1` | `slice(0, -1)` and `slice(-1)` count from the end. The item goes before the last element, and the two halves do not line up the way you expect. |
The negative case deserves care. splice also accepts negative indexes, but the two methods do not always agree in how they treat out-of-range values. If the index comes from user input or from a computation, validate it first.
function insertAt(list, index, item) {
const safeIndex = Math.max(0, Math.min(index, list.length));
return [
...list.slice(0, safeIndex),
item,
...list.slice(safeIndex),
];
}A small helper like this keeps the clamping in one place. It also returns a new array and never touches list, so you can call it as setItems(insertAt(items, index, newItem)).
Inserting several items
The pattern extends naturally. Place more than one item between the two halves.
const next = [
...items.slice(0, index),
...newItems,
...items.slice(index),
];
setItems(next);You do not need a loop, and you do not need multiple setter calls. One new array holds the whole result.
Inserting when the position depends on previous state
An event handler reads items from the snapshot of the render in which the handler was created. If two inserts run in the same event, the second one uses the same stale snapshot and overwrites the first.
// Wrong: both calls read the same items snapshot.
function insertTwo() {
setItems([...items.slice(0, 1), { id: 100, name: 'A' }, ...items.slice(1)]);
setItems([...items.slice(0, 1), { id: 101, name: 'B' }, ...items.slice(1)]);
}Only the second insert survives, because both calls started from the same items. An updater function fixes this. React passes it the latest queued state, so each call builds on the result of the one before.
function insertTwo() {
setItems((prev) => [...prev.slice(0, 1), { id: 100, name: 'A' }, ...prev.slice(1)]);
setItems((prev) => [...prev.slice(0, 1), { id: 101, name: 'B' }, ...prev.slice(1)]);
}After both updaters run, the list holds the first item, then B, then A, then the rest. B comes before A because the second insert also uses index 1, so it lands ahead of the item inserted first.
Common mistakes
- Calling
spliceon state. It returns the removed items, not the array, and it mutates the original. WritingsetItems(items.splice(1, 0, x))sets state to an empty array, because nothing was removed. - Copying first, then splicing, and forgetting the copy. If you do copy, it works:
const next = [...items]; next.splice(index, 0, x); setItems(next);. Mutating a copy is fine because the copy is not state yet. The failure comes from skipping the copy. - Using the index as the
key. After an insert in the middle, every later item has a new index. React then matches items to the wrong previous elements. Local state such as input text can jump to the wrong row. Use a stableid. - Generating the id during render. Create ids in the event handler, as the examples do, so a re-render does not produce a new id for the same item.
- Off-by-one on the index. Inserting before an item uses
index. Inserting after it usesindex + 1.
Cost
Each insert copies the whole array, so it takes time proportional to the array's length. For lists of tens or hundreds of items this cost does not matter. For very large lists, the render work usually dominates the copy, so measure before you optimize.
The copy is shallow. The item objects inside the new array are the same objects as in the old one. That is the behavior you want here, because you are not changing them, and React can still tell that the array is new.
Exercise
A component holds const [tasks, setTasks] = useState(['a', 'b', 'c']). Write a handler body that inserts the string 'x' at index 2 without mutating the array. Then state what the array looks like afterward, and explain what goes wrong if the handler calls tasks.splice(2, 0, 'x') followed by setTasks(tasks).
Show answer
Use setTasks([...tasks.slice(0, 2), 'x', ...tasks.slice(2)]). The result is ['a', 'b', 'x', 'c']. With splice followed by setTasks(tasks), the array in the current snapshot is changed in place and the setter receives the same reference it already holds. React may bail out of the render because the value looks unchanged, so the screen can fail to update even though the data changed. Mutating state also breaks the snapshot model.
Exercise
A button handler inserts an item at index 0 twice in a row using setItems([newItem, ...items]) each time. Only one item appears. Fix it, and say why the fix works.
Show answer
Use updater functions: setItems((prev) => [first, ...prev]); setItems((prev) => [second, ...prev]);. Both calls in the original handler read the same items snapshot, so the second overwrites the first. An updater function receives the latest queued state, so the second call starts from the result of the first. The final order is second, first, then the original items.