Sub topic 11
Inserting at a Specific Position
This chapter assumes you know useState, event handlers, the spread operator, and slice. It builds on the earlier chapter about adding items to the end of an array.
Why the obvious tool fails
Adding to the end of an array is easy with [...items, newItem]. Adding in the middle looks like a job for splice. But splice mutates the array it is called on. If you call it on the array in state, you change the current snapshot in place, which breaks the read-only rule from earlier chapters.
You could copy the array first and then splice the copy. That works, but a second pattern reads more clearly and needs no temporary variable.
Slice before, slice after
slice never mutates. It returns a new array. So you can cut the old array into two halves at the target position and place the new item between them:
const index = 1;
const newItem = { id: 99, title: 'Inserted' };
const next = [
...items.slice(0, index),
newItem,
...items.slice(index),
];
setItems(next);items.slice(0, index) holds everything before the position. items.slice(index) holds everything from the position onward. Spreading both into a new array literal gives a fresh array with the item in the right place. React sees a new reference and re-renders.
A complete example
This component inserts a new item at position 1 each time you click the button.
import { useState } from 'react';
let nextId = 3;
export default function FruitList() {
const [items, setItems] = useState([
{ id: 0, title: 'Apple' },
{ id: 1, title: 'Banana' },
{ id: 2, title: 'Cherry' },
]);
function insertAt(index, title) {
setItems([
...items.slice(0, index),
{ id: nextId++, title },
...items.slice(index),
]);
}
return (
<>
<button onClick={() => insertAt(1, 'Inserted')}>
Insert at position 1
</button>
<ul>
{items.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</>
);
}Each new object gets a unique id from the counter. The key uses that id, not the array index. This matters for insertion. If you keyed by index, every item after the insertion point would get a new key, and React would mix up which item is which. That causes wrong input values or lost state in list items.
Common errors
- Calling
items.splice(...)and thensetItems(items). The setter receives the same reference, so React may skip the render. - Keying by index. Insertions shift indexes. Use a stable id.
- Passing an out-of-range index.
slicedoes not throw. With an index larger than the length,slice(0, index)returns the whole array andslice(index)returns an empty one. The item ends up at the end. - Reading
itemsafter several updates in one handler. Two inserts in the same event both start from the same snapshot. Use an updater function, covered later in this tutorial, for that case.
Exercise
You have items in state and the id of an existing item, afterId. Write the body of a function that inserts newItem immediately after that item without mutating state.
Show answer
Find the position first, then slice around it: const i = items.findIndex((item) => item.id === afterId); setItems([...items.slice(0, i + 1), newItem, ...items.slice(i + 1)]);. Adding 1 puts the new item after the match instead of before it. If findIndex returns -1, i + 1 is 0 and the item lands at the start, so guard against that case.