Sub topic 2
Storing to-dos in state
This chapter assumes you know JavaScript arrays, objects, destructuring, and spread syntax. It also assumes you have a React project created with Vite and understand basic JSX. You will store the to-do list in component state and see how React reads and updates it.
Why a plain variable is not enough
A component is a function that React calls to produce a screen. If you keep the list in a regular let variable, changing it does not tell React to call the function again. The screen stays stale, and the variable is reset on each call anyway.
State solves both problems. It is a value React stores for the component between renders. When you update it through the setter function, React schedules a new render.
Declaring state with useState
useState takes an initial value and returns a pair: the current value and a setter.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState("");
return (
<main>
<h1>To-do</h1>
<p>You have {todos.length} tasks.</p>
</main>
);
}The array starts empty. The text state will hold what the user types in the form, which you wire up in a later chapter. Each to-do will be an object with three fields:
id: a unique value that identifies the item.title: the text the user entered.done: a boolean for completion.
How a state update works
Calling a setter does not change the variable in the code that is already running. It asks React to render again with the new value.
Each render sees its own snapshot of the state. Inside one event handler, todos keeps the same value even after you call setTodos.
Replace state, do not mutate it
React compares the old and new state by reference. If you change an array in place with push, the reference stays the same and React may skip the update. Build a new array instead.
// Wrong: mutates the existing array
todos.push({ id: crypto.randomUUID(), title: "Buy milk", done: false });
setTodos(todos);
// Right: creates a new array
setTodos([...todos, { id: crypto.randomUUID(), title: "Buy milk", done: false }]);The chapter on immutable updates covers toggling and deleting. For now, remember the rule: copy, change the copy, pass it to the setter.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `todos.push(...)` | The UI does not update | Use `setTodos([...todos, item])` |
| Reading `todos` right after `setTodos` | You see the old value | Use the new value you computed, or wait for the next render |
| Calling `useState` inside an `if` or loop | Error about hook order | Call hooks at the top level of the component |
| Starting with `useState()` and calling `todos.map` | Crash, because `todos` is `undefined` | Use `useState([])` |
Try it
Add a button that appends a fixed to-do so you can watch the count change.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([]);
function addSample() {
setTodos((prev) => [
...prev,
{ id: crypto.randomUUID(), title: "Sample task", done: false },
]);
}
return (
<main>
<h1>To-do</h1>
<button type="button" onClick={addSample}>Add sample</button>
<p>You have {todos.length} tasks.</p>
</main>
);
}Exercise
A teammate writes todos.push(newItem); setTodos(todos); and the list on screen never changes. Why, and what is the fix?
Show answer
push changes the existing array, so setTodos receives the same reference as before. React sees no change and does not re-render. Create a new array instead: setTodos([...todos, newItem]).
Exercise
After calling setTodos([...todos, item]) inside a handler, you log todos.length. Does it include the new item? Why?
Show answer
No. The handler runs with the snapshot of state from the current render. The new value appears in the next render.