Today I learned about derived state in React while working on my grocery app Listo, and it totally cleared my confusion!
What is Derived State? π€
Derived state is information you donβt store directly, but calculate from your existing state.
For example, in Listo we have a grocery list:
const [items, setItems] = useState([
{ id: 1, name: "Milk", packed: true },
{ id: 2, name: "Eggs", packed: false },
{ id: 3, name: "Bread", packed: true },
]);
We want to show:
Total items π§Ί
Packed items β
Percentage packed π
Instead of storing all of these in state, we derive them from items:
const numItems = items.length;
const numPackedItems = items.filter(item => item.packed).length;
const percentPacked = numItems === 0 ? 0 : Math.round((numPackedItems / numItems) * 100);
See? We only store the real state (items), everything else is calculated automatically.
Why Derived State Rocks π
No duplicate state β fewer bugs
Always accurate β UI matches the data
Clean code β easier to maintain
Using Derived State in a Component
Hereβs how I show stats in Listo:
function Stats({ numItems, numPackedItems, percentPacked }) {
return (
<footer className="stats">
<em>
{percentPacked === 100
? "π All items packed! Ready to go! π"
: `π§Ί You added ${numItems} items, and packed ${numPackedItems} (${percentPacked}%)`}
</em>
</footer>
);
}
Takeaway β¨
βStore only the real data, calculate everything else.β
Derived state keeps your React apps clean, reliable, and easy to read. Even in my grocery app Listo, this approach made the stats section super easy to manage.
Top comments (0)