Skip to content

Sharing State Between Components

The Course
•
20 min study

On Day 4, App passed a row a function to call. Today that idea becomes the main way components work together.

The problem

Here are three pieces: a form that adds a task, a list that shows the tasks, and a count of what's left. The form and the list are separate components. Where should the tasks live?

  • Not in AddTask: then TaskList couldn't see them.
  • Not in TaskList: then AddTask couldn't add to them.

The answer is the closest common parent of everything that needs them. Here that's App. Moving state up like this is called lifting state up.

State in the parent React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function AddTask({ onAdd }) { const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; onAdd(title.trim()); setTitle(""); } return ( <form onSubmit={handleSubmit}> <input type="text" aria-label="New task" placeholder="New task" value={title} onChange={(e) => setTitle(e.target.value)} />{" "} <button type="submit">Add</button> </form> ); } import { useState } from "react"; import AddTask from "./AddTask.jsx"; import TaskList from "./TaskList.jsx"; export default function App() { const [tasks, setTasks] = useState([ { id: 1, title: "Read about forms", done: true }, { id: 2, title: "Build a controlled input", done: false }, ]); function addTask(title) { setTasks([...tasks, { id: Date.now(), title, done: false }]); } function toggleTask(id) { setTasks(tasks.map((task) => (task.id === id ? { ...task, done: !task.done } : task))); } const left = tasks.filter((task) => !task.done).length; return ( <main> <h1>Tasks</h1> <p className="muted">{left} left to do</p> <AddTask onAdd={addTask} /> <TaskList tasks={tasks} onToggle={toggleTask} /> </main> ); } export default function TaskList({ tasks, onToggle }) { return ( <ul> {tasks.map((task) => ( <li key={task.id}> <label> <input type="checkbox" checked={task.done} onChange={() => onToggle(task.id)} />{" "} {task.title} </label> </li> ))} </ul> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; } label { display: block; margin: 0.5rem 0; } input, select, button { font: inherit; } input[type="text"], input[type="number"], select { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } .error { color: #b42318; margin: 0.25rem 0; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Add a task and tick some boxes. The count above both components stays right, because it's computed from the same tasks.

Data down, events up

Read how the pieces connect:

  • App owns tasks and the functions that change it, addTask and toggleTask:

    JavaScript
    function addTask(title) {
      setTasks([...tasks, { id: Date.now(), title, done: false }]);
    }
    
    function toggleTask(id) {
      setTasks(tasks.map((task) => (task.id === id ? { ...task, done: !task.done } : task)));
    }
  • It passes data down as props: <TaskList tasks={tasks} ... />.

  • It passes callbacks down too: onAdd={addTask}, onToggle={toggleTask}.

  • Children send events up by calling those callbacks: onAdd(title.trim()). They say what happened; App decides how the state changes:

    JavaScript
    function handleSubmit(event) {
      event.preventDefault();
      if (title.trim() === "") return;
      onAdd(title.trim());
      setTitle("");
    }

Notice that AddTask still has state of its own: the text being typed. Nobody else needs it until the form is submitted, so it stays where it's used. Put state as low as it can go, and as high as it needs to be.

Predict

TaskList calls onToggle(task.id), but TaskList never mentions setTasks. If you deleted toggleTask from App and its onToggle prop, what would happen when you tick a box?

Check your prediction

The checkbox wouldn't change, and React would call onToggle, which is now undefined, so the console would show onToggle is not a function. The child can only ask; it's up to the parent to provide the function that changes the state.

Your turn

Exercise

A Clear finished button in its own component

Write a ClearFinished component with one prop, onClear, that shows a Clear finished button. Use it in App under the list, so clicking it removes every finished task. App keeps all the task state.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function AddTask({ onAdd }) { const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; onAdd(title.trim()); setTitle(""); } return ( <form onSubmit={handleSubmit}> <input type="text" aria-label="New task" placeholder="New task" value={title} onChange={(e) => setTitle(e.target.value)} />{" "} <button type="submit">Add</button> </form> ); } import { useState } from "react"; import AddTask from "./AddTask.jsx"; import TaskList from "./TaskList.jsx"; export default function App() { const [tasks, setTasks] = useState([ { id: 1, title: "Read about forms", done: true }, { id: 2, title: "Build a controlled input", done: false }, ]); function addTask(title) { setTasks([...tasks, { id: Date.now(), title, done: false }]); } function toggleTask(id) { setTasks(tasks.map((task) => (task.id === id ? { ...task, done: !task.done } : task))); } const left = tasks.filter((task) => !task.done).length; return ( <main> <h1>Tasks</h1> <p className="muted">{left} left to do</p> <AddTask onAdd={addTask} /> <TaskList tasks={tasks} onToggle={toggleTask} /> </main> ); } export default function TaskList({ tasks, onToggle }) { return ( <ul> {tasks.map((task) => ( <li key={task.id}> <label> <input type="checkbox" checked={task.done} onChange={() => onToggle(task.id)} />{" "} {task.title} </label> </li> ))} </ul> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; } label { display: block; margin: 0.5rem 0; } input, select, button { font: inherit; } input[type="text"], input[type="number"], select { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } .error { color: #b42318; margin: 0.25rem 0; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The tasks live in App, so only App can change them. ClearFinished doesn't need to know about tasks at all: it only reports that it was clicked, through the function it was given. The work of deciding which tasks to keep happens in App.

Hint 2: a first step

Write ClearFinished first and pass it onClear={() => console.log("clear!")} from App. Click the button: the console shows clear!, so the child is reporting correctly. Now replace that arrow function with a function in App that sets the tasks to a new array. Which array method from Day 4 keeps only some items?

Show one solution
JSX
function ClearFinished({ onClear }) {
  return <button onClick={onClear}>Clear finished</button>;
}

In App:

JavaScript
function clearFinished() {
  setTasks(tasks.filter((task) => !task.done));
}
JSX
<TaskList tasks={tasks} onToggle={toggleTask} />
<ClearFinished onClear={clearFinished} />

Was this article helpful?

Your response is saved on this device.