AI Hints
Home›React Tutorial›Thinking in React
React · Lesson 36 of 120

Derived Values

Compute, don't store.

⏱ 2 min read▶ Video at 28:18🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

If a value can be calculated from state, don't store it in state. Calculate it while rendering. Then it can never get out of sync.

  • Can you calculate it?
  • Don't store it
  • Never out of sync

A basket total

The basket items are state. The item count and the total are calculated from them, every render. When we add a helmet, both update automatically. Run it.

App.jsxjsx
import { useState } from "react";

export default function App() {
  const [items, setItems] = useState([{ name: "Trail 500", price: 849.5 }]);

  const count = items.length;
  const total = items.reduce((sum, item) => sum + item.price, 0);

  return (
    <div className="box">
      <p>{count} items, total £{total.toFixed(2)}</p>
      <button id="add" onClick={() => setItems([...items, { name: "Helmet", price: 40 }])}>
        Add a helmet
      </button>
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#add"}]

Store or compute

Storing the total in its own state means updating it every time the items change. Forget once, and it's wrong. Computing it from the items is always right.

Stored

  • const [total, setTotal]Update by handCan drift

Computed

  • const total = items.reduce(...)AutomaticAlways right

Summary

Compute values from state while rendering, instead of storing them. Next, a new section on effects.

Key takeaways
  • Compute
  • Don't store
  • Always in sync
Next up: useEffect — side effects