Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
reactreact-routerroutingclean-code

Prefer React Router state over manual URL parsing

Use hooks like `useMatches` or `useMatch` with stable route IDs to detect active routes instead of manually parsing the `pathname` string.

PR: Feat/FCK-2116 - Hide transaction disclaimer on profil tab on person profile #320Created: Dec 7, 2025

Bad example

Old codetsx
1import { useLocation } from 'react-router-dom';
2
3export function NavigationHighlight() {
4 const { pathname } = useLocation();
5
6 // Bad: Manually parsing URL strings with Regex is brittle
7 // Breaks if the URL scheme changes (e.g. to /u/:id/profile)
8 const isUserProfile = /^\/user\/\d+\/profile$/.test(pathname);
9
10 return <nav className={isUserProfile ? 'active' : ''}>...</nav>;
11}

Explanation (EN)

Manually parsing `pathname` using Regex or string methods is fragile and duplicates routing logic. If the route path changes in the configuration, this logic will silently break.

Objašnjenje (HR)

Ručno parsiranje `pathname` varijable pomoću regularnih izraza je krhko i duplicira logiku rutiranja. Ako se putanja rute promijeni u konfiguraciji, ova logika će prestati raditi bez upozorenja.

Good example

New codetsx
1import { useMatches } from 'react-router-dom';
2
3// Route config: { path: 'user/:id/profile', id: 'user-profile', ... }
4
5export function NavigationHighlight() {
6 const matches = useMatches();
7
8 // Good: Uses React Router's internal knowledge and stable IDs
9 const isUserProfile = matches.some((match) => match.id === 'user-profile');
10
11 return <nav className={isUserProfile ? 'active' : ''}>...</nav>;
12}

Explanation (EN)

Using `useMatches` checks the actual matched route objects provided by the router. Relying on a stable route `id` ensures the logic remains valid even if the URL path structure changes.

Objašnjenje (HR)

Korištenje `useMatches` provjerava stvarne objekte ruta koje router prepoznaje. Oslanjanje na stabilan `id` rute osigurava da logika ostane ispravna čak i ako se struktura URL putanje promijeni.

Notes (EN)

Ensure you explicitly assign unique `id` properties to your route definitions in `createBrowserRouter` or similar configs for this pattern to work reliably.

Bilješke (HR)

Osigurajte da eksplicitno dodijelite jedinstvena `id` svojstva definicijama ruta u `createBrowserRouter` ili sličnim konfiguracijama kako bi ovaj obrazac pouzdano radio.