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).
Localize browser patches with scoped listeners
Fix element-specific browser quirks using scoped event listeners on the target element instead of global interaction tracking.
Bad example
| 1 | const [hasUserInteracted, setHasUserInteracted] = useState(false); |
| 2 | const inputRef = useRef<HTMLInputElement>(null); |
| 3 |
|
| 4 | // BAD: Tracking global user interaction to gate a local input behavior (e.g., preventing auto-focus) |
| 5 | useEffect(() => { |
| 6 | const markInteraction = () => setHasUserInteracted(true); |
| 7 | window.addEventListener('pointerdown', markInteraction); |
| 8 | window.addEventListener('keydown', markInteraction); |
| 9 | return () => { |
| 10 | window.removeEventListener('pointerdown', markInteraction); |
| 11 | window.removeEventListener('keydown', markInteraction); |
| 12 | }; |
| 13 | }, []); |
| 14 |
|
| 15 | const handleFocus = (e: React.FocusEvent) => { |
| 16 | if (!hasUserInteracted) { |
| 17 | e.target.blur(); // Prevents Safari auto-focus |
| 18 | } |
| 19 | }; |
Explanation (EN)
This code introduces complex global state and window listeners solely to manage the behavior of a single input element. It pollutes the component with unrelated concerns and renders the logic fragile and hard to maintain.
Objašnjenje (HR)
Ovaj kod uvodi složeno globalno stanje i listenere na 'window' objektu samo kako bi upravljao ponašanjem jednog input elementa. To zagađuje komponentu nepovezanim problemima i čini logiku krhkom te teškom za održavanje.
Good example
| 1 | const inputRef = useRef<HTMLInputElement>(null); |
| 2 |
|
| 3 | // GOOD: Self-contained fix using a one-time listener directly on the element |
| 4 | useEffect(() => { |
| 5 | const input = inputRef.current; |
| 6 | if (!input) return; |
| 7 |
|
| 8 | const controller = new AbortController(); |
| 9 | |
| 10 | // Patch: Intercept and neutralize the first focus event (Safari quirk) |
| 11 | input.addEventListener( |
| 12 | 'focus', |
| 13 | (event) => { |
| 14 | invariant(event.currentTarget instanceof HTMLInputElement); |
| 15 | event.currentTarget.blur(); |
| 16 | }, |
| 17 | { signal: controller.signal, once: true } |
| 18 | ); |
| 19 |
|
| 20 | return () => controller.abort(); |
| 21 | }, []); |
Explanation (EN)
The logic is fully contained within a single effect targeting only the specific element. Using `once: true` and `AbortController` handles the browser quirk cleanly without tracking global user state.
Objašnjenje (HR)
Logika je u potpunosti sadržana unutar jednog efekta koji cilja samo specifični element. Korištenje `once: true` i `AbortController` rješava problem preglednika na čist način bez praćenja globalnog stanja korisnika.