Rules Hub
Coding Rules Library
Derive state defaults from option constants
Avoid hardcoding initial state values that must correspond to a specific list of options; reference the options source directly.
Bad example
| 1 | const PAGE_SIZES = [10, 25, 50]; |
| 2 |
|
| 3 | export const Pagination = () => { |
| 4 | // Bad: 10 is hardcoded. If PAGE_SIZES changes to [20, 50, 100], |
| 5 | // this default becomes invalid or inconsistent. |
| 6 | const [pageSize, setPageSize] = useState(10); |
| 7 |
|
| 8 | return (/* ... */); |
| 9 | }; |
Explanation (EN)
Hardcoding the initial value creates a hidden dependency. If the configuration constant (`PAGE_SIZES`) changes, the hardcoded default might become invalid (e.g., if 10 is removed), leading to bugs or inconsistent UI states.
Objašnjenje (HR)
Hardkodiranje početne vrijednosti stvara skrivenu ovisnost. Ako se konfiguracijska konstanta (`PAGE_SIZES`) promijeni, hardkodirana zadana vrijednost može postati nevažeća (npr. ako se 10 ukloni), što dovodi do bugova ili nekonzistentnog stanja sučelja.
Good example
| 1 | const PAGE_SIZES = [10, 25, 50] as const; |
| 2 |
|
| 3 | export const Pagination = () => { |
| 4 | // Good: The default is explicitly tied to the source of truth. |
| 5 | // It automatically adapts if the order or values in PAGE_SIZES change. |
| 6 | const [pageSize, setPageSize] = useState(PAGE_SIZES[0]); |
| 7 |
|
| 8 | return (/* ... */); |
| 9 | }; |
Explanation (EN)
By deriving the default state directly from the `PAGE_SIZES` constant (e.g., `PAGE_SIZES[0]`), the code guarantees that the initial state is always a valid, existing option, even if the configuration values change in the future.
Objašnjenje (HR)
Izvođenjem zadanog stanja izravno iz konstante `PAGE_SIZES` (npr. `PAGE_SIZES[0]`), kod jamči da je početno stanje uvijek valjana i postojeća opcija, čak i ako se konfiguracijske vrijednosti promijene u budućnosti.