javascript / intermediate
Snippet
Encapsulating Business Logic in React State with Immutable Domain Entity Classes
Using object-oriented Domain Value Objects with Object.freeze enforces immutability and centralizes calculation invariants. When storing class instances in React state, methods return fresh instances instead of mutating properties, ensuring seamless integration with React shallow equality checks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import React, { useState } from 'react';class Money {constructor(cents, currency = 'EUR') {this.cents = Math.round(cents);this.currency = currency;Object.freeze(this);}add(other) {if (this.currency !== other.currency) {throw new Error('Currency mismatch');}return new Money(this.cents + other.cents, this.currency);}format() {return new Intl.NumberFormat('de-DE', {style: 'currency',currency: this.currency}).format(this.cents / 100);}}export function BudgetTracker() {const [total, setTotal] = useState(() => new Money(1000));const handleDeposit = () => {setTotal((prev) => prev.add(new Money(500)));};return (<div><h2>Current Balance: {total.format()}</h2><button onClick={handleDeposit}>Deposit 5,00 €</button></div>);}
react
Breakdown
1
Object.freeze(this);
Freezes the newly instantiated class instance to prevent runtime property mutations.
2
return new Money(this.cents + other.cents, this.currency);
Returns a new immutable instance upon addition, fulfilling React state purity requirements.
3
setTotal((prev) => prev.add(new Money(500)));
Updates component state using the domain method which produces a new object reference.