Rules Hub
Code Ruleset
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Initialize state from a prop instead of syncing via useEffect
When state only needs the prop's initial value, pass it to useState directly rather than setting it in a mount-time useEffect.
Bad example
| 1 | const [selected, setSelected] = useState(false); |
| 2 | useEffect(() => { setSelected(initialSelected); }, []); |
Explanation (EN)
An effect used solely for initial state adds an avoidable initial render with the wrong value.
Objašnjenje (HR)
Effect koji služi samo postavljanju početnog stanja dodaje nepotreban prvi render s pogrešnom vrijednošću.
Good example
| 1 | const [selected, setSelected] = useState(initialSelected); |
Explanation (EN)
The initial selection is present on the first render; later prop updates are intentionally ignored.
Objašnjenje (HR)
Početni odabir postoji već u prvom renderu; kasnije promjene propa namjerno se ignoriraju.
Notes (EN)
Initialize state from a prop only when the component contract consumes that prop once at mount. Check subsequent prop updates, remount keys and any intended enter animation.
Exceptions / Tradeoffs (EN)
If state must keep tracking later prop changes (controlled/derived from a changing prop), you need a different pattern; this applies when only the initial value matters. Do not remove synchronization required by later prop updates or a deliberately deferred animation transition. Use a controlled value or explicit reset contract where appropriate.
Iznimke / Tradeoffi (HR)
Ovo vrijedi kada prop određuje samo početnu vrijednost. Ako stanje mora pratiti kasnije promjene propa ili odgođenu animaciju, zadrži potrebnu sinkronizaciju ili odredi kontroliranu vrijednost i jasan ugovor reseta.