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).
Prefer refs for latest state in stable callbacks
When a useCallback only needs the latest state for a lookup or imperative action, read it from a ref instead of depending on the whole state collection.
Bad example
| 1 | const [transactions, setTransactions] = useState<Transaction[]>([]); |
| 2 |
|
| 3 | const updateTransaction = useCallback(async (transactionId: number) => { |
| 4 | const transaction = transactions.find(item => item.id === transactionId); |
| 5 | await saveTransaction(transaction); |
| 6 | }, [transactions]); |
Explanation (EN)
Depending on the whole state collection recreates the callback every time that collection changes, even when the callback only needs the latest item lookup at call time.
Objašnjenje (HR)
Ovisnost o cijeloj state kolekciji ponovno stvara callback svaki put kad se kolekcija promijeni, iako callback pri pozivu treba samo zadnji lookup.
Good example
| 1 | const [transactions, setTransactions] = useState<Transaction[]>([]); |
| 2 | const transactionsRef = useRef(transactions); |
| 3 | transactionsRef.current = transactions; |
| 4 |
|
| 5 | const updateTransaction = useCallback(async (transactionId: number) => { |
| 6 | const transaction = transactionsRef.current.find(item => item.id === transactionId); |
| 7 | await saveTransaction(transaction); |
| 8 | }, []); |
Explanation (EN)
The ref keeps the latest state available without forcing the callback to change identity on every collection update. This keeps imperative callbacks stable while still reading fresh data.
Objašnjenje (HR)
Ref drzi zadnji state dostupnim bez potrebe da callback mijenja identitet kod svake promjene kolekcije. Tako callback ostaje stabilan, a i dalje cita svjeze podatke.
Notes (EN)
Use this pattern when the callback only needs read access to the latest value at execution time. This is especially useful for event handlers, mutation callbacks, or async actions passed to children.
Bilješke (HR)
Koristi ovaj obrazac kada callback pri izvrsavanju treba samo read pristup zadnjoj vrijednosti. Posebno je koristan za event handlere, mutation callbackove i async akcije koje se prosljedjuju dalje.
Exceptions / Tradeoffs (EN)
Keep state in the dependency list when the callback should intentionally be recreated as that state changes, or when the state participates in derived logic that should stay inside React's dependency model.
Iznimke / Tradeoffi (HR)
Zadrzi state u dependency listi kada callback namjerno treba biti ponovno stvoren pri promjeni tog statea, ili kada state sudjeluje u izvedenoj logici koja treba ostati unutar React dependency modela.