Sub topic 2
Storing to-dos in state
This chapter covers how a React to-do app holds its list in memory with useState. It assumes you know JavaScript functions, arrays, objects, destructuring, and spread syntax. It also assumes you can read basic JSX and that you have a Vite React project that runs with npm run dev. Props, forms, and keys get their own chapters, so this one keeps the UI minimal and concentrates on the state.
Why a to-do list needs state
A function component runs again every time React renders it. Any ordinary variable you declare inside it is created fresh on each run. If you write let todos = [] and push to it, the change is lost on the next render, and React never learns that anything changed.
State solves both problems. It is a value that React stores outside your function, between renders. When you update it, React schedules a new render so the screen matches the new value.
| Approach | Survives re-render? | Triggers re-render? |
|---|---|---|
| `let todos = []` inside the component | No | No |
| `const todos = []` at module level, mutated | Yes | No |
| `const [todos, setTodos] = useState([])` | Yes | Yes |
The module-level variable in the second row keeps its value, but React cannot see it change, so the screen goes stale. It is also shared by every instance of the component. Neither is what you want for UI data.
Calling useState
useState takes the initial value and returns an array with two items: the current value and a setter function. You normally destructure them.
import { useState } from "react";
const [todos, setTodos] = useState([]);The initial value [] is used only on the first render. On later renders React ignores the argument and returns the value it has stored.
Two rules apply to every hook, including useState:
- Call hooks only at the top level of a component or a custom hook. Never call them inside conditions, loops, or nested functions.
- Call hooks only from React function components or custom hooks, not from ordinary functions.
React tracks state by call order. The first useState call in a component maps to the first slot, the second call to the second slot, and so on. A conditional call would shift the slots and mix up the values.
Shaping a to-do
Before you store anything, decide what one to-do looks like. This app uses a small object:
{ id: "a1b2", title: "Buy milk", done: false }idis a unique identifier. You will use it for keys and for finding an item to toggle or delete. Do not use the array index as the id, because indexes change when items are removed.titleis the text the user typed.donerecords whether the item is completed.
Store only what you cannot compute from other values. The number of remaining items, for example, can be calculated from todos, so it does not belong in state. A later chapter covers this in detail.
A first working example
The following component keeps the list in state and adds an item when you click a button. It is deliberately simple. The proper form with a controlled input comes in a later chapter.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([
{ id: "1", title: "Learn state", done: false },
]);
function addSample() {
const next = {
id: crypto.randomUUID(),
title: "Sample task " + (todos.length + 1),
done: false,
};
setTodos([...todos, next]);
}
return (
<main>
<h1>To-do</h1>
<button type="button" onClick={addSample}>
Add sample
</button>
<p>{todos.length} items</p>
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</main>
);
}Each click calls setTodos with a new array. React stores that array, re-renders App, and the map call produces one <li> per item. crypto.randomUUID() is available in current browsers on secure contexts, which includes localhost.
What happens on a state update
The setter does not change the variable todos in the code that is already running. It tells React to render again with the new value.
React compares the new value to the old one with Object.is. If both are the same reference, React skips the re-render. This comparison is the reason you must pass a new array instead of changing the existing one.
Common errors
Mutating state directly
// Wrong: changes the existing array, then passes the same reference
todos.push(newTodo);
setTodos(todos);The reference is identical, so React sees no change and may not update the screen. Even when it does render, mutation causes subtle bugs in memoized components and in React's development tools. Create a new array instead:
setTodos([...todos, newTodo]);The next chapters apply the same rule to toggling and deleting.
Reading state right after setting it
function addAndLog() {
setTodos([...todos, newTodo]);
console.log(todos.length); // still the old length
}State is a snapshot. In one render, todos has one fixed value, and every function created in that render sees that value. The new array appears in the next render.
Several updates from the same snapshot
Because handlers see a snapshot, two updates in a row that both read todos overwrite each other:
function addTwo() {
setTodos([...todos, first]);
setTodos([...todos, second]); // replaces the first update
}Both calls build their array from the same old todos, so only second is added. When a new value depends on the previous one, pass an updater function. React calls it with the latest pending state, in order.
function addTwo() {
setTodos((current) => [...current, first]);
setTodos((current) => [...current, second]);
}Both items are added. Use the updater form whenever the next state is computed from the previous state and more than one update could be queued, or when the update happens inside a delayed callback such as a timeout.
Expensive initial values
useState(readFromDisk()) calls readFromDisk on every render, even though React uses the result only once. Pass a function instead and React calls it only on the first render:
const [todos, setTodos] = useState(() => loadTodos());This is called lazy initialization. A later chapter uses it to read from localStorage.
Storing derived values
A tempting pattern is to add a second state variable such as const [count, setCount] = useState(0) and update it next to todos. The two values can drift apart if one update is missed. Compute todos.length during render instead.
Strict Mode and double rendering
If your Vite project wraps App in <StrictMode>, React renders components twice in development to expose impure code. It also calls updater functions twice. This is why updaters and initializers must be pure: they should compute a result from their inputs and nothing else. Do not generate ids or push to outside arrays inside an updater. Create the id before calling the setter, as addSample does above.
// Risky: the updater runs twice in development, so two different ids are created
setTodos((current) => [...current, { id: crypto.randomUUID(), title, done: false }]);// Safe: the id is created once, outside the updater
const id = crypto.randomUUID();
setTodos((current) => [...current, { id, title, done: false }]);The second version ensures the updater returns the same result every time it is called with the same input.
Quick reference
useState(initial)returns[value, setValue].- The initial value is used once. Pass a function to compute it lazily.
- Never mutate state. Build a new array or object.
- State is a snapshot for the current render. Use the updater form when the next value depends on the previous one.
- Keep state minimal. Derive everything else during render.
Exercise
A handler runs setTodos([...todos, a]); setTodos([...todos, b]); and only b appears in the list. Why does this happen, and how do you rewrite it so both appear?
Show answer
Both calls build their new array from the same snapshot of todos, so the second call replaces the first result instead of adding to it. Use updater functions: setTodos((current) => [...current, a]); setTodos((current) => [...current, b]);. React applies them in order, and each receives the result of the previous one.
Exercise
Why is todos.push(item); setTodos(todos); a bug, and which comparison does React use to decide whether to re-render?
Show answer
push mutates the existing array, and setTodos receives the same reference. React compares the new and old values with Object.is, finds them identical, and can skip the re-render. Passing a new array, such as [...todos, item], gives a different reference and triggers a render.