Skip to content

Derived Values

The Course
•
15 min study

A derived value is one you can compute from state or props: a count, a total, a filtered list, a label. The previous lesson said to compute them instead of storing them. Here is what happens when they're stored.

A count kept in state React · 4 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"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [doneCount, setDoneCount] = useState(1); function finish(id) { setCards(cards.map((card) => (card.id === id ? { ...card, column: "done" } : card))); setDoneCount(doneCount + 1); } function remove(id) { setCards(cards.filter((card) => card.id !== id)); } return ( <main> <h1>Study Board</h1> <p>{doneCount} of {cards.length} done</p> <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong> <span className="muted">({card.column})</span>{" "} {card.column !== "done" && ( <button onClick={() => finish(card.id)} aria-label={`Finish ${card.title}`}>Finish</button> )}{" "} <button onClick={() => remove(card.id)} aria-label={`Remove ${card.title}`}>Remove</button> </li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Predict

The header says 1 of 4 done. Press Finish on Read about reducers, then Remove on Practice useState. What does the header say after each click?

Check your prediction

After Finish: 2 of 4 done, which is right. After Remove: 2 of 3 done, but only one card is still done. finish remembered to update doneCount; remove didn't. Every handler that changes cards has to keep doneCount in step, and one forgot:

JavaScript
function finish(id) {
  setCards(cards.map((card) => (card.id === id ? { ...card, column: "done" } : card)));
  setDoneCount(doneCount + 1);
}

function remove(id) {
  setCards(cards.filter((card) => card.id !== id));
}

Compute it instead

Delete the doneCount state and the setDoneCount call, and compute the count during render:

JavaScript
const doneCount = cards.filter((card) => card.column === "done").length;

Now no handler needs to know about it. Repeat the experiment: the count is right after every click, because it's recalculated from cards every render.

"But isn't recalculating slow?"

Filtering a few hundred items takes a fraction of a millisecond. Computing during render is the right default. Day 6 shows how to measure when something is genuinely slow, and how to cache it with useMemo if it is.

Don't sync with an effect either

A tempting fix is an effect that copies the count into state:

JavaScript
useEffect(() => {
  setDoneCount(cards.filter((card) => card.column === "done").length);
}, [cards]);

It shows the right number in the end, but every change renders twice: once with the old count and once with the new one. The code is also longer than computing it directly. Day 5 covers when effects are the right tool. Copying state into other state is never one of them.

Exercise

Total minutes left

Under the header, show the minutes left, such as 60 minutes left: the sum of minutes for every card that isn't done. Compute it during render.

Your working space React · 4 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"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [doneCount, setDoneCount] = useState(1); function finish(id) { setCards(cards.map((card) => (card.id === id ? { ...card, column: "done" } : card))); setDoneCount(doneCount + 1); } function remove(id) { setCards(cards.filter((card) => card.id !== id)); } return ( <main> <h1>Study Board</h1> <p>{doneCount} of {cards.length} done</p> <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong> <span className="muted">({card.column})</span>{" "} {card.column !== "done" && ( <button onClick={() => finish(card.id)} aria-label={`Finish ${card.title}`}>Finish</button> )}{" "} <button onClick={() => remove(card.id)} aria-label={`Remove ${card.title}`}>Remove</button> </li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The total follows from the current cards. It should be recomputed with them, rather than synchronized by another setter.

Hint 2: a first step

Do it in two steps. First get the cards that aren't done, and show how many there are: at the start it should say 3. Then turn that array into one number by adding up their minutes. Which array method combines all the items into a single value, and what should the running total start at?

Show one solution
JavaScript
const minutesLeft = cards
  .filter((card) => card.column !== "done")
  .reduce((sum, card) => sum + card.minutes, 0);
JSX
<p className="muted">{minutesLeft} minutes left</p>

At the start, three cards aren't done: 20 + 15 + 25 = 60 minutes. After finishing Read about reducers, 40.

Was this article helpful?

Your response is saved on this device.