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 synchronous DOM access over unnecessary microtasks
Avoid wrapping DOM logic in microtasks if the element is already mounted and accessible.
Bad example
| 1 | import { useEffect, useRef } from 'react'; |
| 2 |
|
| 3 | export function SearchInput() { |
| 4 | const inputRef = useRef<HTMLInputElement>(null); |
| 5 |
|
| 6 | useEffect(() => { |
| 7 | // Bad: Unnecessary microtask for an element that is guaranteed to be mounted |
| 8 | queueMicrotask(() => { |
| 9 | if (document.activeElement === inputRef.current) { |
| 10 | inputRef.current?.blur(); |
| 11 | } |
| 12 | }); |
| 13 | }, []); |
| 14 |
|
| 15 | return <input ref={inputRef} />; |
| 16 | } |
Explanation (EN)
Wrapping immediate DOM interactions in a microtask adds unnecessary complexity and async behavior. Since `useEffect` runs after the component has mounted and the ref is populated, deferral is not needed for static elements.
Objašnjenje (HR)
Zamotavanje trenutnih DOM interakcija u mikro-zadatak dodaje nepotrebnu složenost i asinkrono ponašanje. Budući da se `useEffect` pokreće nakon što se komponenta montira i referenca popuni, odgoda nije potrebna za statične elemente.
Good example
| 1 | import { useEffect, useRef } from 'react'; |
| 2 |
|
| 3 | export function SearchInput() { |
| 4 | const inputRef = useRef<HTMLInputElement>(null); |
| 5 |
|
| 6 | useEffect(() => { |
| 7 | // Good: Execute logic synchronously as the element is already visible |
| 8 | if (document.activeElement === inputRef.current) { |
| 9 | inputRef.current?.blur(); |
| 10 | } |
| 11 | }, []); |
| 12 |
|
| 13 | return <input ref={inputRef} />; |
| 14 | } |
Explanation (EN)
The DOM logic runs synchronously within the effect, ensuring the state is consistent immediately. This is cleaner, easier to debug, and avoids potential race conditions.
Objašnjenje (HR)
DOM logika se izvršava sinkrono unutar efekta, osiguravajući da je stanje odmah konzistentno. Ovo je čišće, lakše za debugiranje i izbjegava potencijalne probleme s utrkom (race conditions).
Notes (EN)
Only use microtasks or timeouts if you are waiting for a browser paint, a layout recalculation, or an element that renders asynchronously (e.g., inside a just-opened portal or dialog).
Bilješke (HR)
Koristite mikro-zadatke ili timeout samo ako čekate iscrtavanje preglednika (paint), ponovni izračun rasporeda (layout) ili element koji se asinkrono renderira (npr. unutar upravo otvorenog portala ili dijaloga).