Rules Hub
Coding Rules Library
Prefer route IDs over pathnames for route matching
Use stable route IDs to identify routes programmatically instead of relying on brittle URL path strings.
Bad example
| 1 | import { useMatches } from 'react-router'; |
| 2 |
|
| 3 | export function useIsProfilePage() { |
| 4 | const matches = useMatches(); |
| 5 | // BAD: Relies on the URL structure remaining constant |
| 6 | // Breaks if URL changes to '/account/profile' or similar |
| 7 | return matches.some((match) => |
| 8 | match.pathname.includes('/user/profile') |
| 9 | ); |
| 10 | } |
Explanation (EN)
The logic relies on checking `pathname` strings to determine the active route. This is brittle because changing the URL structure (e.g., renaming `/user` to `/account`) breaks the logic without warning, and partial matching can lead to false positives.
Objašnjenje (HR)
Logika se oslanja na provjeru `pathname` stringova za određivanje aktivne rute. To je krhko jer promjena strukture URL-a (npr. preimenovanje `/user` u `/account`) tiho lomi logiku, a djelomično podudaranje može dovesti do lažnih pozitiva.
Good example
| 1 | // routes.tsx |
| 2 | // { path: 'user/profile', id: 'user-profile', Component: Profile } |
| 3 |
|
| 4 | import { useMatches } from 'react-router'; |
| 5 |
|
| 6 | export function useIsProfilePage() { |
| 7 | const matches = useMatches(); |
| 8 | // GOOD: Checks against a stable internal identifier |
| 9 | return matches.some((match) => match.id === 'user-profile'); |
| 10 | } |
Explanation (EN)
The logic uses a stable `id` assigned to the route definition. This decouples the route identity from its URL representation, allowing paths to change (e.g., for translation, SEO, or refactoring) without breaking the application logic.
Objašnjenje (HR)
Logika koristi stabilan `id` dodijeljen definiciji rute. To odvaja identitet rute od njezine URL reprezentacije, omogućujući promjenu putanja (npr. za prijevod, SEO ili refaktoriranje) bez lomljenja logike aplikacije.