Explain it simply
Explain it simply
In this lesson you combine the pieces from earlier lessons into a Todo app that really works. The user types a task, presses Add, and it joins the list. When there are no tasks, the app says so.
Picture two notebooks on a shelf. One holds the text being typed right now (text); the other holds the saved task list (todos). Everything on screen is drawn by reading those two notebooks. To change a notebook, you do not erase a page; you swap in a whole new notebook, which is how React notices the change.
Problem → Why → Solution
The problem: pressing Add shows nothing
In the first attempt, addTodo pushes into the todos array and calls setTodos(todos). A console.log shows the task is in the array, but nothing appears on screen. Only when the user types another character do the tasks suddenly show up.
The same developer also keeps a separate remaining state and calls setRemaining(remaining + 1) on every add. When a delete feature arrives, they forget to decrease it, and the counter no longer matches the number of tasks.
const [todos, setTodos] = useState([]);
const [remaining, setRemaining] = useState(0); // duplicated information
function addTodo(event) {
event.preventDefault();
todos.push({ id: Date.now(), text }); // mutates the current array
setTodos(todos); // same reference: React skips it
setRemaining(remaining + 1); // must be kept in sync by hand
}Why doesn't the screen update?
When you call setTodos, React compares the new value with the old one using Object.is. push modifies the same array, so the reference does not change, React concludes nothing changed and skips the re-render. remaining stores information that can be computed from todos, so two places must be kept in sync by hand.
Core concept: minimal state, derived values, immutable updates
Before writing code for a project, plan it in four steps. A small Todo app is the easiest place to practise this plan, and it works the same way for much bigger apps.
1. List what the UI shows and does
A heading, an input, an Add button, the task list and a message when the list is empty. The user can do two things: type and submit.
2. Find the minimum state
Only values that change over time and cannot be computed from something else are state. Here that is just text and todos. Whether the list is empty and how many tasks remain can be computed from todos on every render.
3. Decide where the state lives
Put state in the closest common parent of every component that uses it. For now that is TodoApp alone. When TodoForm and TodoList are split out later, the state stays in TodoApp and travels down as props.
4. Create a new value on every update
When changing an array or object, leave the original untouched and return a new one. The reference changes, and React re-renders.
| Goal | Immutable pattern | Avoid |
|---|---|---|
| Add an item | [...todos, newTodo] | todos.push(newTodo) |
| Change one item | todos.map(t => t.id === id ? { ...t, done: true } : t) | t.done = true |
| Remove an item | todos.filter(t => t.id !== id) | todos.splice(index, 1) |
Every item needs an id that never changes. Using the map index as the key means deleting one item shifts the index of every item after it, and React can attach checkbox state to the wrong row. Toggle and delete are also safer when they look items up by id, because an index in a filtered list does not match the index in the original array.
- The user types or submits
- A handler computes new state
- React calls the component again
- Render derives counts and messages
Handlers only change state; they never touch the DOM directly. Everything on screen is a result of the latest state.
General pattern
const [draft, setDraft] = useState('');
const [items, setItems] = useState([]);
const isEmpty = items.length === 0; // derived, not stored
function handleSubmit(event) {
event.preventDefault();
if (!draft.trim()) return;
setItems([...items, { id: makeId(), value: draft.trim() }]);
setDraft('');
}One piece of state for the input, one for the list, and everything else derived. The submit handler prevents the default, validates, updates with a new array and clears the input.
The first version of the Todo app
This version adds tasks and shows them. The text state controls the input and the todos state holds the list. On submit it trims spaces, adds the task with a new array only if it is not empty, and clears the input. The challenge adds toggling, deleting and filtering.
import { useState } from 'react';
function TodoApp() {
const [text, setText] = useState('');
const [todos, setTodos] = useState([]);
function addTodo(event) {
event.preventDefault();
const cleanText = text.trim();
if (!cleanText) return;
const newTodo = {
id: Date.now(),
text: cleanText
};
setTodos([...todos, newTodo]);
setText('');
}
return (
<main>
<h1>React Todo Mini Project</h1>
<form onSubmit={addTodo}>
<input
value={text}
onChange={event => setText(event.target.value)}
placeholder="Write a task..."
/>
<button type="submit">Add</button>
</form>
{todos.length === 0 ? (
<p>No tasks yet. Add your first task.</p>
) : (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
)}
</main>
);
}
export default TodoApp;Code breakdown
- Two pieces of state
const [todos, setTodos] = useState([]);There are only two pieces of state, text and todos. Whether the list is empty is computed from todos.length, not stored.
- Stop the page reload
event.preventDefault();A form submit reloads the page by default; without this line all state would be lost.
- Reject empty input
if (!cleanText) return;After trim(), an empty string is falsy, so input made only of spaces exits without adding a task.
- New array, not push
setTodos([...todos, newTodo]);The spread copies todos into a new array and appends newTodo. The new reference is what makes React re-render.
- Empty state vs list
{todos.length === 0 ? (A ternary shows the message when the list is empty and the <ul> otherwise. Each item has key={todo.id}, so React can tell items apart correctly.
Every time you type a task and hit Add, a new task gets added to the list. If there are no tasks yet, an empty message shows up.Splitting into components
As the app grows, split the form and the list into their own components. The state stays in TodoApp; TodoForm receives an onAdd callback and TodoList receives the todos array as props. Children do not own the data; they only tell the parent that something happened. This is called lifting state up.
function TodoForm({ onAdd }) {
const [text, setText] = useState('');
function handleSubmit(event) {
event.preventDefault();
if (!text.trim()) return;
onAdd(text.trim());
setText('');
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="new-todo">New task</label>
<input id="new-todo" value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">Add</button>
</form>
);
}
function TodoList({ todos }) {
if (todos.length === 0) return <p>No tasks yet. Add your first task.</p>;
return <ul>{todos.map((t) => <li key={t.id}>{t.text}</li>)}</ul>;
}About Date.now() as an id
Date.now() in the example can produce the same id when two items are created within one millisecond, for example during an import or in a test. crypto.randomUUID() is safer; in browsers it needs a secure context such as HTTPS or localhost.
In real projects
In real projects
The shape of this Todo app shows up in many real apps. Adding to a shopping cart, posting a comment and adding a person to a contact list all follow the same flow: control the input, validate on submit, update with a new array, clear the input. The empty-state message is important UI too, because it tells users whether they hit a bug or simply have no data.
As the app grows, todos need to be saved on a server or in localStorage. If state is kept strictly immutable, those changes are easy to add. Switching to useReducer, adding optimistic updates or keeping a history array for an undo feature only works correctly when nothing is mutated.
Common mistakes
Common mistakes
Pushing and calling setTodos(todos)
As the problem section showed, the reference does not change, so React skips the re-render. Tasks appearing suddenly after some unrelated update is the telltale sign of this bug. Use [...todos, newTodo].
Mutating the old object when toggling
const t = todos.find(...); t.done = !t.done; setTodos([...todos]) creates a new array, but the item object is the old one, mutated. Memoized rows can fail to update and undo history breaks. Return { ...t, done: !t.done } inside map instead.
Using the placeholder as the label
The example's input has only a placeholder and no label. The placeholder disappears as soon as you type, and some screen readers do not announce it reliably as the field's name. Add a <label htmlFor>, as the TodoForm in the deeper section does.
Best practices
Best practices
- After adding each feature, try the app in the browser before starting the next one
- Name handlers with a verb and a noun, such as addTodo and toggleTodo
- Try the edge cases yourself: an empty list, input that is only spaces, a very long task
- Add a task using only Tab and Enter, without touching the mouse
Mini challenge
Finish the Todo app
Extend the lesson's Todo app. Each task gets a checkbox to mark it done or not done, and a Delete button. Add an "N tasks left" counter and three filter buttons: All, Active and Done.
- Each todo has id, text and done; create ids with crypto.randomUUID()
- Write toggle immutably with map plus spread, and delete with filter
- Derive the remaining count and the visible list during render; do not store them
- Give the input a label, the filter buttons aria-pressed, and each delete button an aria-label of "Delete <text>"
import { useState } from 'react';
const FILTERS = {
// TODO: all, active, done -> functions that take a todo and return true/false
};
export default function TodoApp({ initialTodos = [] }) {
// TODO: state for text, todos and filter ('all')
// TODO: derive visible (todos filtered by FILTERS[filter]) and remaining
function addTodo(event) {
// TODO: prevent default, trim, ignore empty, add { id, text, done: false }
}
function toggleTodo(id) {
// TODO: map -> copy the matching todo with done flipped
}
function deleteTodo(id) {
// TODO: filter it out
}
// TODO: labelled form, "N tasks left", filter buttons, list or empty message
}Expected: After adding two tasks and checking one, the app shows "1 task left". The Active filter shows only the unchecked task and Done only the checked one. When no task matches, "Nothing here yet." appears.
Show hint
With FILTERS written as { all: () => true, active: (t) => !t.done, done: (t) => t.done }, todos.filter(FILTERS[filter]) gives visible in one line. Mind the singular and plural: "1 task left" versus "2 tasks left".
Show solution
import { useState } from 'react';
const FILTERS = {
all: () => true,
active: (todo) => !todo.done,
done: (todo) => todo.done,
};
export default function TodoApp({ initialTodos = [] }) {
const [text, setText] = useState('');
const [todos, setTodos] = useState(initialTodos);
const [filter, setFilter] = useState('all');
const visible = todos.filter(FILTERS[filter]);
const remaining = todos.filter((todo) => !todo.done).length;
function addTodo(event) {
event.preventDefault();
const clean = text.trim();
if (!clean) return;
setTodos([...todos, { id: crypto.randomUUID(), text: clean, done: false }]);
setText('');
}
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function deleteTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}
return (
<main>
<h1>Todos</h1>
<form onSubmit={addTodo}>
<label htmlFor="new-todo">New task</label>
<input
id="new-todo"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button type="submit">Add</button>
</form>
<p>{remaining} {remaining === 1 ? 'task' : 'tasks'} left</p>
<div role="group" aria-label="Filter tasks">
{Object.keys(FILTERS).map((name) => (
<button
key={name}
aria-pressed={filter === name}
onClick={() => setFilter(name)}
>
{name}
</button>
))}
</div>
{visible.length === 0 ? (
<p>Nothing here yet.</p>
) : (
<ul>
{visible.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => toggleTodo(todo.id)}
/>
{todo.text}
</label>
<button
onClick={() => deleteTodo(todo.id)}
aria-label={`Delete ${todo.text}`}
>
×
</button>
</li>
))}
</ul>
)}
</main>
);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Before coding, list the UI and find the minimum state
- Do not store values you can compute, such as counts, isEmpty or a filtered list
- Add with spread, change with map plus spread, remove with filter
- Forms need preventDefault, a trim check and a real label
- The parent that owns the state passes it to child components as props
React Documentation — React