I Stopped Doing Money Math in React Components
Invoice totals, GST, returns and stock adjustments are too easy to get almost right. I moved those rules into small TypeScript domain modules instead.
Key takeaways
Financial rules are easier to trust when they live outside the component tree.
Decimal-safe arithmetic is only useful when rounding rules are explicit too.
Stock and payment history should be recorded, not silently overwritten.
How it starts
The first calculation usually looks harmless.
A quantity multiplied by a price does not need much architecture. Then discounts arrive. Then GST modes, partial payments, returns and rounding. Before long, a table cell is doing business logic every time it renders.
I moved that work out of React in TallyLite. Monetary calculations live in dedicated TypeScript modules, with Decimal.js used where precision matters. Components receive a result and decide how to present it.
Make the steps visible
An invoice total is easier to debug when each step has a name.
The important change was not just adding a decimal library. I split the calculation into stages: line values, discounts, taxable amount, GST treatment, total and outstanding balance.
Now an edge case has a specific home and a focused test. I do not need to search JSX for a percentage expression and wonder whether the same calculation exists somewhere else.
- Validate the input shape first.
- Use decimal-safe primitives for money.
- Round at deliberate boundaries.
- Store enough information to explain the total later.
Financial rules are easier to trust when they live outside the component tree.
Inventory and returns
I prefer movements over rewriting the current number.
For stock, payments and returns, history is useful. A current quantity tells me where I ended up; movements tell me how I got there.
That is especially useful in TallyLite because the underlying records are visible to the user. Append-style history makes reconciliation much less mysterious.
Financial rules are easier to trust when they live outside the component tree.
The frontend benefit
The components became smaller after the rules moved out.
Once totals, balances and stock effects come from tested domain functions, the UI mainly handles input, feedback and accessibility.
That made refactoring safer and removed a class of “looks fine in the browser” bugs from presentation code.
Financial rules are easier to trust when they live outside the component tree.