Client and server state Recommended
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.
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) };
}
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.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers app interface playbook: https://agentwranglers.se/playbook/app-ui/client-and-server-state/derived-values.