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).
Make registration side effects idempotent for Strict Mode
Effects that register with a non-idempotent external API must guard against Strict Mode's double-invoke by tracking what was already registered.
Bad example
| 1 | useEffect(() => { |
| 2 | // runs twice in Strict Mode dev -> external SDK gets two register calls |
| 3 | externalSdk.register(widgetId); |
| 4 | return () => externalSdk.unregister(widgetId); |
| 5 | }, [widgetId]); |
Explanation (EN)
Strict Mode invokes the effect twice in development, so a non-idempotent register call fires twice and can corrupt the SDK's state or duplicate work.
Objašnjenje (HR)
Strict Mode u developmentu pokreće efekt dvaput, pa se neidempotentni register poziv izvrši dva puta i može pokvariti stanje SDK-a ili udvostručiti posao.
Good example
| 1 | const registeredIds = useRef(new Set<string>()); |
| 2 |
|
| 3 | useEffect(() => { |
| 4 | if (registeredIds.current.has(widgetId)) return; |
| 5 | registeredIds.current.add(widgetId); |
| 6 | externalSdk.register(widgetId); |
| 7 |
|
| 8 | return () => { |
| 9 | registeredIds.current.delete(widgetId); |
| 10 | externalSdk.unregister(widgetId); |
| 11 | }; |
| 12 | }, [widgetId]); |
Explanation (EN)
A ref-held Set makes the registration idempotent: the duplicate Strict Mode run sees the id already registered and skips the external call.
Objašnjenje (HR)
Set čuvan u refu čini registraciju idempotentnom: ponovljeni Strict Mode prolaz vidi da je id već registriran i preskače vanjski poziv.
Notes (EN)
Identifying the right cleanup boundary matters: release only when the component truly unmounts, not on the throwaway Strict Mode unmount.
Bilješke (HR)
Bitno je odrediti pravu granicu čišćenja: oslobađaj resurs samo kad se komponenta stvarno unmounta, a ne na lažnom Strict Mode unmountu.