- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Structuring State
State and Reducers
Structuring State
Most state bugs are structural. If a value can be calculated from another value, storing it means two things that can disagree.
Do not store what you can derive
A value computed from existing state does not need its own state. Compute it during render - it is free, and it can never fall out of sync.
Derived, not stored
jsx
function Cart() {
const [items, setItems] = React.useState([
{ name: "Book", price: 12 },
{ name: "Pen", price: 3 },
])
// Derived on every render. No second state, nothing to keep in sync.
const total = items.reduce((sum, item) => sum + item.price, 0)
const isEmpty = items.length === 0
return (
<div>
<p>{isEmpty ? "Cart is empty" : `${items.length} items, total ${total}`}</p>
<button onClick={() => setItems([...items, { name: "Mug", price: 8 }])}>Add mug</button>{" "}
<button onClick={() => setItems([])}>Empty</button>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Cart />)