Using Stateful List
A stateful list is an array stored in React state, so that adding, removing or editing an item automatically re-renders the list on screen. Static arrays defined in a file are fine for content that never changes, but anything the user interacts with, such as a to-do list, a shopping cart or a list of comments, needs to live in state with useState.
Putting the array in state
You create the state with an initial array, render it with map(), and change it only through the setter function. The key rule is that you never modify the existing array. Instead, you build a new array and pass that to the setter. React compares the old and new references; a new array tells it something changed.
import { useState } from 'react';
const initialTasks = [
{ id: 1, text: 'Revise closures', done: false },
{ id: 2, text: 'Practise flexbox', done: true }
];
function TaskList() {
const [tasks, setTasks] = useState(initialTasks);
const [draft, setDraft] = useState('');
function addTask(event) {
event.preventDefault();
if (!draft.trim()) return;
setTasks(prev => [...prev, { id: crypto.randomUUID(), text: draft.trim(), done: false }]);
setDraft('');
}
function toggle(id) {
setTasks(prev => prev.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
function remove(id) {
setTasks(prev => prev.filter(t => t.id !== id));
}
return (
<>
<form onSubmit={addTask}>
<input value={draft} onChange={e => setDraft(e.target.value)} />
<button>Add</button>
</form>
<ul>
{tasks.map(task => (
<li key={task.id}>
<label>
<input type="checkbox" checked={task.done} onChange={() => toggle(task.id)} />
{task.text}
</label>
<button type="button" onClick={() => remove(task.id)}>Delete</button>
</li>
))}
</ul>
</>
);
}
Immutable recipes for common changes
| Goal | Avoid (mutates) | Use instead |
|---|---|---|
| Add to end | push | [...prev, item] |
| Add to start | unshift | [item, ...prev] |
| Remove | splice | prev.filter(...) |
| Update one item | prev[i].done = true | prev.map(...) returning a copied object |
| Sort or reverse | sort, reverse | toSorted, toReversed, or copy first |
Newer array methods make some of these recipes easier. toSorted(), toReversed() and toSpliced() return changed copies instead of altering the original, and with(index, value) returns a copy with one position replaced. In environments without them, copy first with [...prev] and then call sort() on the copy.
Why the functional setter helps
Passing a function to the setter, as in setTasks(prev => ...), makes React give you the latest state. If two updates happen in the same event, or a handler was created during an earlier render, reading tasks directly might use an outdated array and lose an item. The functional form avoids that.
The push that does nothing
The classic mistake is tasks.push(newTask); setTasks(tasks);. The array has changed, but it is the same array object, so React sees an identical reference and may skip the re-render. Even when something else causes a render, mutating state leads to subtle bugs with memoised components. The same applies to objects inside the array: { ...t, done: !t.done } copies the object instead of editing it.
Also give each item a stable, unique ID when it is created, and use that as the key. Using the array index as a key breaks once items can be removed or reordered, because React may attach a checkbox state to the wrong row.
Finally, avoid storing values you can derive. The number of completed tasks, for instance, can be calculated with tasks.filter(t => t.done).length during rendering. Keeping it in a second state variable means remembering to update both every time, and they will eventually drift apart. Store the list once and compute counts, totals and filtered views from it.
Main points
Keep the array in state, replace it with a new array on every change, use filter, map and spread instead of mutating methods, and key items by stable IDs.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.