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).
Use matchMedia instead of a window resize handler for breakpoint logic
Drive responsive state with matchMedia / MediaQueryList listeners rather than recomputing window.innerWidth on every resize event.
Bad example
| 1 | useEffect(() => { |
| 2 | function onResize() { |
| 3 | setIsNarrow(window.innerWidth < 800); |
| 4 | } |
| 5 | onResize(); |
| 6 | window.addEventListener('resize', onResize); |
| 7 | return () => window.removeEventListener('resize', onResize); |
| 8 | }, []); |
Explanation (EN)
The handler runs on every resize tick and re-reads layout, even when the breakpoint hasn't been crossed.
Objašnjenje (HR)
Handler se izvodi na svaki resize otkucaj i ponovno cita layout, cak i kad granica breakpointa nije presla.
Good example
| 1 | useEffect(() => { |
| 2 | const mql = window.matchMedia('(max-width: 799px)'); |
| 3 | const update = () => setIsNarrow(mql.matches); |
| 4 | update(); |
| 5 | mql.addEventListener('change', update); |
| 6 | return () => mql.removeEventListener('change', update); |
| 7 | }, []); |
Explanation (EN)
matchMedia fires only when the breakpoint boundary is crossed and a single query can combine multiple breakpoints, making the intent declarative.
Objašnjenje (HR)
matchMedia se okida samo kad se prijede granica breakpointa, a jedan upit moze kombinirati vise breakpointova, cineci namjeru deklarativnom.
Exceptions / Tradeoffs (EN)
Use a resize handler when you need the continuous pixel value (e.g. for fluid sizing) rather than discrete breakpoint matching.
Iznimke / Tradeoffi (HR)
Koristi resize handler kad treba kontinuirana vrijednost u pikselima (npr. za fluidno dimenzioniranje), a ne diskretno poklapanje breakpointova.