Sub topic 3
Inserting at a Specific Position
Assume you know JavaScript arrays, slice, map, filter, React function components, and useState. React state is a snapshot, so array updates must create a new array.
Insert an Item at an Index
Use slice to copy the items before and after the insertion point. Then place the new item between those copies.
import { useState } from 'react';
export default function TodoList() {
const [items, setItems] = useState([
{ id: 1, title: 'Read' },
{ id: 2, title: 'Practice' },
]);
function insertItem(index) {
const newItem = { id: 3, title: 'Review' };
setItems([
...items.slice(0, index),
newItem,
...items.slice(index),
]);
}
return (
<button onClick={() => insertItem(1)}>
Insert review
</button>
);
}For an index of 1, the new item appears between the first and second items.
Sort and Reverse a Copy
sort and reverse mutate the array they receive. Copy the array first, then mutate the copy.
function sortByName() {
const next = [...items];
next.sort((a, b) => a.name.localeCompare(b.name));
setItems(next);
}
function reverseItems() {
setItems([...items].reverse());
}Update Objects Inside Arrays
Use map to create a new array and spread the object that changes:
setItems(items.map((item) =>
item.id === id ? { ...item, done: !item.done } : item
));The array and the changed object are new. Unchanged objects can keep their existing references.
Use Updater Functions
When the next value depends on previous state, pass a function to the setter. This is important for multiple queued updates.
setItems((previous) => [
...previous,
{ id: nextId++, title: 'Another item' },
]);Keep State Flat
Deeply nested state requires copying every object on the path to the changed value. Store related records in separate arrays or objects when practical. Flatter state makes updates easier to read and less error-prone.
Use Immer for Deep Updates
Immer lets you write mutation-like code against a draft while producing immutable state:
import { useImmer } from 'use-immer';
const [person, updatePerson] = useImmer({
address: { city: 'London' },
});
updatePerson((draft) => {
draft.address.city = 'Paris';
});Exercise
Why must you copy an array before calling reverse on it?
Show answer
reverse mutates the array it receives. Copying first keeps the current React state unchanged.