Rules Hub
Code Ruleset
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Update only the changed item instead of recomputing the whole collection
When changing one element of an array in a state update, copy and splice that single index rather than mapping every item and computing values you only need for one.
Bad example
| 1 | setValue(prev => prev.map((item, i) => { |
| 2 | const calculatedField = { /* computed for every item */ }; |
| 3 | return index === i ? { ...item, calculatedField } : item; |
| 4 | })); |
Explanation (EN)
Computing the replacement for every element wastes work even though only one item changes.
Objašnjenje (HR)
Good example
| 1 | setValue(previous => previous.map(item => |
| 2 | item.id === targetId ? { ...item, calculatedField: buildField(item) } : item, |
| 3 | )); |
Explanation (EN)
Only the matched item is recalculated, while a stable ID avoids replacing the wrong index after reordering.
Objašnjenje (HR)
Notes (EN)
Compute expensive item-specific work only for the target, preserving immutable state and verifying the target still exists in the updater's current state.
Exceptions / Tradeoffs (EN)
Both map and copying/splice are O(n) for an array copy. A conditional map may be clearer; index identity can go stale after reordering, so prefer a stable ID when appropriate.