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).
Don't default to useEffect for work that doesn't need the DOM
useEffect runs after mount and DOM commit, the latest possible point on the client; work that only needs the browser runtime should run earlier.
Bad example
| 1 | export default function useRegisterElements(tags: string[]) { |
| 2 | useEffect(() => { |
| 3 | for (const tag of tags) { |
| 4 | void defineCustomElement(tag); |
| 5 | } |
| 6 | }, [tags]); |
| 7 | } |
Explanation (EN)
Wrapping this in useEffect defers it until after the component mounts and React commits the DOM, even though defining a custom element class only needs the client JS runtime, not a mounted DOM. useEffect is treated as the default place to run any client-side code, but it's actually the latest point at which it can run; this delays registration for no reason.
Objašnjenje (HR)
Omatanje ovoga u useEffect odgada izvrsavanje dok se komponenta ne montira i React ne izvrsi commit DOM-a, iako za definiranje klase custom elementa treba samo JS runtime na klijentu, a ne montiran DOM. useEffect se tretira kao zadano mjesto za pokretanje bilo kojeg klijentskog koda, no zapravo je to najkasnija tocka u kojoj se on moze izvrsiti; ovo bespotrebno odgada registraciju.
Good example
| 1 | // Client-only module: safe to run at load time, no DOM required. |
| 2 | if (typeof window !== 'undefined') { |
| 3 | for (const tag of tagsForThisRoute) { |
| 4 | void defineCustomElement(tag); |
| 5 | } |
| 6 | } |
Explanation (EN)
Since the work only needs the browser runtime, not a mounted DOM or layout, it runs as soon as the client module is evaluated instead of waiting for React's post-mount effect phase, so registration happens as early as possible.
Objašnjenje (HR)
Buduci da posao treba samo browser runtime, ne montiran DOM ili layout, izvrsava se cim se klijentski modul evaluira, umjesto da ceka Reactovu fazu efekata nakon montiranja, pa se registracija dogodi sto je ranije moguce.
Notes (EN)
Reach for useEffect only when the work genuinely depends on the DOM being mounted or on cleanup tied to the component's lifecycle; otherwise prefer running it at module scope in a client-only file, or synchronously during render.
Bilješke (HR)
Posegni za useEffectom samo kada posao stvarno ovisi o montiranom DOM-u ili o cleanupu vezanom uz zivotni ciklus komponente; inace je bolje pokrenuti ga na razini modula u client-only fileu, ili sinkrono tijekom rendera.