Sub topic 8
Lifting state up to the App component
This chapter assumes you know useState, props, controlled inputs, and immutable updates with map and filter. Here you will move all the to-do state into one place, so every component that needs the list reads from the same copy.
The problem with scattered state
Suppose the form component keeps its own todos array and the list component keeps another. When the form adds an item, the list never finds out, because React state belongs to one component and is not shared. The same happens if the footer needs a count of remaining tasks.
The fix is to lift the state up. You find the closest common parent of every component that needs the data, and you store the state there. In this app, that parent is App.
Data flows down, events flow up
Once App owns todos, it passes data to children as props. Children can't change that data directly. They call callback functions that App also passes down, and App runs the setTodos call.
Building it
The form keeps only the text of the input, which is local to it. It reports a finished title upward.
import { useState } from "react";
function AddTodoForm({ onAdd }) {
const [text, setText] = useState("");
function handleSubmit(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
onAdd(title);
setText("");
}
return (
<form onSubmit={handleSubmit}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
);
}
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.title}
</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}
function TodoList({ todos, onToggle, onDelete }) {
return (
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
</ul>
);
}
export default function App() {
const [todos, setTodos] = useState([]);
function addTodo(title) {
setTodos([...todos, { id: crypto.randomUUID(), title, done: false }]);
}
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>To-do</h1>
<AddTodoForm onAdd={addTodo} />
<TodoList todos={todos} onToggle={toggleTodo} onDelete={deleteTodo} />
</main>
);
}The three update functions all live in App, next to the state they change. A child never calls setTodos. It calls onToggle(todo.id), and App decides what that means.
Deciding what to lift
Not every piece of state should move up. Use this rule:
| State | Who needs it | Where it lives |
|---|---|---|
| `todos` | Form, list, and later the footer | `App` |
| Text in the new-task input | Only the form | `AddTodoForm` |
Lift state only as far as the nearest common parent. Putting everything in App makes it re-render for every keystroke and clutters it.
A common error is passing onToggle={toggleTodo(todo.id)}. That calls the function during render. Pass a function instead: onChange={() => onToggle(todo.id)}.
Exercise
The footer needs to show how many to-dos are not done. Where should that count be calculated, and should it get its own useState?
Show answer
Calculate it in App (or in the footer, from a todos prop), using todos.filter((t) => !t.done).length. It should not get its own useState, because it can be computed from todos, and a second copy could fall out of sync.