Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Use functional updates when next state depends on previous
When new state is derived from the current value (counters, list prepends), pass an updater function so concurrent updates don't clobber each other.
Bad example
| 1 | // Reads a captured snapshot; two quick updates can both start |
| 2 | // from the same `count`/`items` and one update is lost. |
| 3 | const addItem = (item) => { |
| 4 | setItems([item, ...items]); |
| 5 | setCount(count + 1); |
| 6 | }; |
Explanation (EN)
Computing from the closed-over value means rapid successive calls all start from the same stale snapshot, so updates get dropped and counts drift.
Objašnjenje (HR)
Racunanje iz zatvorene vrijednosti znaci da brzi uzastopni pozivi svi krenu od istog zastarjelog snapshota, pa se azuriranja gube i brojaci se razilaze.
Good example
| 1 | // Functional updates always build on the latest committed state. |
| 2 | const addItem = (item) => { |
| 3 | setItems(prev => [item, ...prev]); |
| 4 | setCount(prev => prev + 1); |
| 5 | }; |
Explanation (EN)
Functional updaters receive the most recent state, so concurrent or batched updates compose correctly without lost writes.
Objašnjenje (HR)
Funkcionalni updateri primaju najnovije stanje, pa se konkurentna ili grupirana azuriranja ispravno slazu bez izgubljenih zapisa.
Notes (EN)
This is also why exposing a raw setter (which supports functional updates) is sometimes preferable to a plain value callback when consumers must increment counts safely.
Bilješke (HR)
Zato je ponekad bolje izloziti sirovi setter (koji podrzava funkcionalna azuriranja) nego obican value callback kad konzumenti moraju sigurno inkrementirati brojace.
Exceptions / Tradeoffs (EN)
If the new value doesn't depend on the previous one (a direct replacement), passing the value directly is fine.
Iznimke / Tradeoffi (HR)
Ako nova vrijednost ne ovisi o prethodnoj (izravna zamjena), prosljedjivanje vrijednosti izravno je u redu.