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 activeElement checks over interaction listeners for autofocus detection
Detect browser autofocus by checking document.activeElement on mount instead of tracking global user interaction events.
Bad example
| 1 | import { useState, useEffect } from 'react'; |
| 2 |
|
| 3 | export function SearchInput() { |
| 4 | const [userInteracted, setUserInteracted] = useState(false); |
| 5 |
|
| 6 | // Tracking global interaction just to guess if focus is native or user-driven |
| 7 | useEffect(() => { |
| 8 | const markInteraction = () => setUserInteracted(true); |
| 9 | window.addEventListener('pointerdown', markInteraction); |
| 10 | window.addEventListener('keydown', markInteraction); |
| 11 | return () => { |
| 12 | window.removeEventListener('pointerdown', markInteraction); |
| 13 | window.removeEventListener('keydown', markInteraction); |
| 14 | }; |
| 15 | }, []); |
| 16 |
|
| 17 | const onFocus = () => { |
| 18 | if (!userInteracted) { |
| 19 | // Assume autofocus and block behavior |
| 20 | return; |
| 21 | } |
| 22 | // Normal behavior |
| 23 | }; |
| 24 |
|
| 25 | return <input onFocus={onFocus} />; |
| 26 | } |
Explanation (EN)
Tracking global events to determine if a focus was user-initiated is fragile and adds unnecessary complexity. It pollutes the component with global side effects solely to infer a state that is already available in the DOM.
Objašnjenje (HR)
Praćenje globalnih događaja kako bi se utvrdilo je li fokus inicirao korisnik je krhko i dodaje nepotrebnu složenost. To zagađuje komponentu globalnim nuspojavama isključivo radi zaključivanja stanja koje je već dostupno u DOM-u.
Good example
| 1 | import { useRef, useEffect } from 'react'; |
| 2 |
|
| 3 | export function SearchInput() { |
| 4 | const inputRef = useRef<HTMLInputElement>(null); |
| 5 |
|
| 6 | useEffect(() => { |
| 7 | // If the element is already focused on mount, it is browser autofocus |
| 8 | if (document.activeElement === inputRef.current) { |
| 9 | // Handle autofocus case (e.g., blur it or suppress side effects) |
| 10 | inputRef.current.blur(); |
| 11 | } |
| 12 | }, []); |
| 13 |
|
| 14 | return <input ref={inputRef} />; |
| 15 | } |
Explanation (EN)
Checking `document.activeElement` on mount is a direct and reliable way to detect browser autofocus. It eliminates the need for global event listeners and manual state synchronization.
Objašnjenje (HR)
Provjera `document.activeElement` pri montiranju izravan je i pouzdan način za otkrivanje automatskog fokusa preglednika. Time se eliminira potreba za globalnim slušačima događaja i ručnom sinkronizacijom stanja.