DEV Community

Usama
Usama

Posted on

Learn Derived State in React with Listo πŸ›’βœ¨

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 },
]);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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)