Sub topic 8
Lifting state up to the App component
This chapter assumes you can write function components, pass props, use useState, and update arrays with map, filter, and spread syntax without mutating them. You should also know how a controlled input works. Here you decide which component should own the to-do list, and you rewire the app around that choice.
Why state needs to move
Suppose the form component keeps its own todos array and adds new items to it. The list component, which is a sibling of the form, needs those items to render them. Siblings cannot read each other's state. React passes data in one direction only, from parent to child through props.
The fix is to move the state to the closest component that sits above every component that needs it. This is called lifting state up. In this app, TodoForm adds items, TodoList shows them, and a later chapter's counter will read them. The closest common parent is App, so App owns todos.
Lifting state has two parts:
- The parent holds the state and passes the current value down as props.
- The parent also passes down functions that change the state. Children call them when something happens.
Data flows down, and events flow up.
The dotted arrows are function calls. A child never edits the array. It reports what the user did and lets the owner decide how the state changes.
Deciding what to lift
Not all state should move up. Lift only what more than one component needs. Keep the rest local.
| State | Who needs it | Where it lives |
|---|---|---|
| `todos` array | form (adds), list (shows), later the counter | `App` |
| Draft text in the "new task" input | only the form | `TodoForm` |
| Which filter is selected (later chapter) | filter buttons and the visible list | `App` |
The draft text is a good example of state that stays local. If the whole app re-rendered on every keystroke because App held the text, you would do extra work for no benefit. Nothing outside the form cares about half-typed text.
A useful test is to ask who reads the value and who changes it. If the answer is one component, keep it there. If the answer is two or more, lift it.
The refactored app
Start with App. It holds the list and defines the three functions that change it.
import { useState } from "react";
import TodoForm from "./TodoForm";
import TodoList from "./TodoList";
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>
<TodoForm onAdd={addTodo} />
<TodoList todos={todos} onToggle={toggleTodo} onDelete={deleteTodo} />
</main>
);
}addTodo now takes a plain title. App creates the id and the done flag, so the rules for what a to-do looks like live in one place.
TodoForm keeps its own draft text. When the user submits, it hands the cleaned title to onAdd and clears its own input.
import { useState } from "react";
export default function TodoForm({ 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>
);
}TodoList receives the array and the callbacks. It has no state of its own. It maps each to-do to a TodoItem and forwards the callbacks.
import TodoItem from "./TodoItem";
export default function TodoList({ todos, onToggle, onDelete }) {
return (
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={onToggle}
onDelete={onDelete}
/>
))}
</ul>
);
}TodoItem is the component from the earlier chapter. It is presentational, meaning it only renders what it is given.
export default 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>
);
}The key goes on TodoItem inside TodoList, because that is where the array is mapped. Putting it inside TodoItem on the <li> would have no effect.
Trace one click to see the full loop:
- The user checks a box.
onChangerunsonToggle(todo.id). onToggleisApp'stoggleTodo. It builds a new array withmapand callssetTodos.- React re-renders
App. It passes the newtodosdown, andTodoItemshows the checked state.
Common errors
Copying props into state
This is the most frequent mistake after lifting.
// Problem: the copy never updates after the first render
function TodoItem({ todo }) {
const [done, setDone] = useState(todo.done);
// ...
}useState uses its argument only on the first render. If App changes todo.done, the child's copy stays stale. Two sources of truth will drift apart. Read todo.done from props and call a callback to change it.
Calling the handler during render
// Wrong: runs immediately on every render
<button onClick={onDelete(todo.id)}>Delete</button>
// Right: passes a function that runs on click
<button onClick={() => onDelete(todo.id)}>Delete</button>The wrong version calls onDelete while rendering. That updates state during a render, which causes a loop or an error such as "Too many re-renders".
Mutating the parent's array in a child
A child receives the same array object that App holds. If a child calls todo.done = true or todos.push(...), React has no signal that anything changed. The screen may not update, and other components see the edit anyway. Children should treat props as read-only. All changes go through the callbacks, which create new arrays.
Stale values with several updates in one event
setTodos(todos.map(...)) uses the todos value from the current render. If one event handler calls two such updates, the second one overwrites the first, because both start from the same old array. When an update depends on the previous state, pass an updater function:
function addTodo(title) {
setTodos((prev) => [
...prev,
{ id: crypto.randomUUID(), title, done: false },
]);
}React calls the updater with the latest queued state. This version is safe even if a handler calls it more than once. For single-click handlers the direct form works fine. The updater form costs little, so many teams use it by default. A reducer, covered in a later chapter, removes this concern altogether.
Passing props through layers that do not use them
TodoList receives onToggle and onDelete only to hand them to TodoItem. This is called prop drilling. Two layers are fine. If a callback has to pass through four or five components that ignore it, consider composition first, such as passing already-built elements as children. Context, covered in a later chapter, is the next option. Do not reach for context in an app this small.
Checking the result
After the refactor, behavior should be identical to the single-file version. You can confirm the ownership split in React Developer Tools. App shows a todos hook, TodoForm shows only its text hook, and TodoList and TodoItem show no hooks at all. If a child that should be presentational has state, ask whether that state is really local.
The structure also prepares the next steps. Filtering and counting can be added in App without touching the form or the item. A reducer can replace the three handler functions without changing any child, because children only see onAdd, onToggle, and onDelete.
Exercise
You want to add a "Clear completed" button in a new component, ClearButton, that removes every to-do where done is true. It is rendered next to TodoList. Where should the logic that removes the items live, and what does ClearButton receive as props?
Show answer
The logic belongs in App, because App owns todos. Add a function such as function clearCompleted() { setTodos(todos.filter((t) => !t.done)); } and render <ClearButton onClear={clearCompleted} />. ClearButton receives only the onClear callback and calls it from its onClick as onClick={onClear}. It does not need the array, and it must not change it.
Exercise
A teammate writes const [done, setDone] = useState(todo.done) inside TodoItem and uses done for the checkbox. After App toggles the item through another path, the checkbox does not change. Why, and what is the fix?
Show answer
useState uses its initial value only on the first render, so the child's done is a copy that never follows the prop. The fix is to delete that local state, use todo.done from props for checked, and call onToggle(todo.id) so that App, the single owner, changes the value.