APP-32Recommended
Compute values instead of storing them
Compute totals, counts, filtered lists and labels from the source data when you render. Never keep them in their own state to update by hand.
How to do it
Keep one source, such as the list of cart lines, and compute the total from it in a function. Memoise only when a profiler shows the computation is slow. A stored copy goes stale the first time someone forgets to update it. The database side is to keep one fact in one place.
Examples
TypeScript example
export function cartSummary(lines: CartLine[]) {
const totalMinor = lines.reduce((sum, line) => sum + line.unitPriceMinor * line.quantity, 0);
return { totalMinor, itemCount: lines.reduce((sum, line) => sum + line.quantity, 0) };
}
Python example
def cart_summary(lines: list[CartLine]) -> dict:
return {
"total_minor": sum(line.unit_price_minor * line.quantity for line in lines),
"item_count": sum(line.quantity for line in lines),
}
How to check
A search of components and stores for state named total, count or filtered, such as setTotal( or state.itemCount =, finds no matches.
Sources
Related rules
- DAT-5 Keep one fact in one place in Data and databases
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/app-ui/client-and-server-state/derived-values">Agent Wranglers web app interface playbook</a>. In code you write, add a comment next to it with the same link.