Navigation with React Router

Navigation with React Router in React: --- A large organisation's mailroom sorts every incoming letter at a wooden sorting frame.


The Analogy: A Mailroom's Address-Sorting Frame

A large organisation's mailroom sorts every incoming letter at a wooden sorting frame. Pinned across the frame is a list of sorting rules, each pairing an address pattern with a pigeonhole: "anything for the 4th floor goes in slot 12," "Suite 400 goes in slot 3." A clerk reads a letter's address, finds the rule that fits, and drops the letter into that rule's pigeonhole. The letter never leaves the building to be re-sorted by the national post -- the whole routing happens on the frame, in place.

Some rules have a blank to fill in. A rule reading "Room ___, Floor 3 -> slot 9" matches any room on the third floor, and the clerk notes the room number as they file it. That captured value travels with the letter, so whoever empties slot 9 knows exactly which room it was for. A rule with no blanks, like "Suite 400," matches only that one exact address. And a final catch-all bin sits at the end of the frame for any letter whose address fits no rule at all, so nothing is ever simply dropped on the floor.

When two rules could both fit a letter, the more specific one wins. A letter to "Suite 400" matches both the exact "Suite 400" rule and the general "Suite ___" rule, and the clerk always chooses the exact one -- it does not matter which rule was pinned up first. Specificity, not the order the rules happen to hang in, decides the pigeonhole. The exact address beats the blank-filling pattern, and the blank-filling pattern beats the everything-else catch-all bin.

The frame's failure modes are all about the rules. Two rules of equal specificity that overlap leave the clerk guessing which slot to use -- ambiguous sorting. A rule written too greedily, whose blank swallows the entire address, quietly captures letters meant for more exact bins and hides them. And if nobody pinned up a catch-all bin, every unmatched letter has nowhere to go and piles up unhandled -- the mailroom equivalent of a URL that matches no route and renders a blank screen.

Syntax or Core Structure

You wrap the app in a router, declare routes as pattern-to-element pairs inside <Routes>, and navigate with <Link> instead of <a> so the browser never does a full reload:

import { BrowserRouter, Routes, Route, Link, useParams } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/users/42">User 42</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/users/:id" element={<UserProfile />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

function UserProfile() {
  const { id } = useParams();  // "42" -- always a string
  return <h1>User {id}</h1>;
}

That renders in a browser, so it has no console output. The core behaviour -- "match a pathname against a pattern and extract its params" -- is a pure function we can run. A pattern matches when it has the same number of segments and every static segment is equal; a :name segment matches anything and captures it; "*" is the catch-all:

function matchRoute(pattern, pathname) {
  if (pattern === "*") return {};  // catch-all matches anything
  const p = pattern.split("/").filter(Boolean);
  const u = pathname.split("/").filter(Boolean);
  if (p.length !== u.length) return null;
  const params = {};
  for (let i = 0; i < p.length; i++) {
    if (p[i][0] === ":") {
      params[p[i].slice(1)] = u[i];
    } else if (p[i] !== u[i]) {
      return null;
    }
  }
  return params;
}

console.log(matchRoute("/users/:id", "/users/42"));
console.log(matchRoute("/users/:id", "/users/42/edit"));
console.log(matchRoute("/about", "/about"));

Output:

{ id: '42' }
null
{}

The first path has two segments that line up with /users/:id, so users matches literally and :id captures "42". The second has three segments against a two-segment pattern, so the length check fails and it returns null -- no match. The third matches exactly with no dynamic segment, so it returns an empty params object. A route is nothing more than this: a pattern, a match test, and the params it pulls out.

Technical Depth: Matching, Ranking, and In-Place Navigation

Dynamic segments become params

Every :name segment in a matched route becomes a key in the params object, whatever the path actually held. The table shows three patterns resolved against a path:

Route patternURL pathparams
/users/:id/users/42id = 42
/posts/:cat/:slug/posts/js/hookscat = js, slug = hooks
/about/about(none)
console.log(matchRoute("/posts/:cat/:slug", "/posts/js/hooks"));

Output:

{ cat: 'js', slug: 'hooks' }

Both blanks are filled in order: cat captures "js" and slug captures "hooks". In a component these arrive through useParams(), and -- this is the part people forget -- every captured value is a string that matched anything in that slot, so a numeric id arrives as "42" and must be validated, not trusted.

A param is not optional, either. A :id segment demands a segment to fill it, so the bare parent path does not match a pattern that expects an id:

console.log(matchRoute("/users/:id", "/users"));

Output:

null

/users has one segment against a two-segment pattern, so the length check rejects it. If you want both /users (a list) and /users/:id (one user) to render, they are two separate routes -- or a parent route with an index child -- not one pattern stretched to cover both.

Most-specific route wins, not first-listed

When several patterns match one path, React Router picks the most specific rather than the first written. We can score specificity the way the frame ranks rules: a static segment outranks a param, which outranks a splat.

function score(pattern) {
  return pattern.split("/").filter(Boolean).map(function (seg) {
    if (seg === "*") return 0;
    if (seg[0] === ":") return 1;
    return 2;
  }).reduce(function (a, b) { return a + b; }, 0);
}

function resolve(routes, pathname) {
  const matched = routes
    .filter(function (r) { return matchRoute(r.pattern, pathname) !== null; })
    .sort(function (a, b) { return score(b.pattern) - score(a.pattern); });
  return matched.length ? matched[0].name : "NotFound";
}

const routes = [
  { pattern: "/users/:id", name: "UserProfile" },
  { pattern: "/users/new", name: "NewUser" },
  { pattern: "*", name: "NotFound" }
];
console.log(resolve(routes, "/users/new"));
console.log(resolve(routes, "/users/42"));
console.log(resolve(routes, "/nope/nope"));

Output:

NewUser
UserProfile
NotFound

For /users/new, both /users/:id (score 3) and /users/new (score 4) match, and the higher score wins, so NewUser renders -- even though /users/:id is listed first. For /users/42 only the dynamic route fits, giving UserProfile. For /nope/nope nothing but the catch-all matches, so NotFound. The exact rule beat the blank-filling rule with no reordering.

Links navigate in place; the server is not asked

Clicking a <Link> swaps the matched view and updates the URL without fetching a new document; an <a href> would tear down the page and reload from the server, losing all in-memory state. The client-side navigation is just "resolve the new path, render its view, same document":

function navigate(routes, toPath) {
  return { documentReloaded: false, view: resolve(routes, toPath) };
}
console.log(navigate(routes, "/users/42"));

Output:

{ documentReloaded: false, view: 'UserProfile' }

The document is not reloaded and the view resolves to UserProfile -- the letter moved within the frame instead of being remailed. That is the whole point of client-side routing: the URL and UI change together, instantly, without a round-trip.

Programmatic navigation and route guards

Not all navigation comes from a click. After a form submits, or when an unauthenticated visitor asks for a protected page, code navigates with the function from useNavigate(). A route guard is a pure decision: given the auth state and the requested path, either allow the target or redirect to the login page.

function guard(isAuthed, target) {
  if (!isAuthed && target !== "/login") {
    return { redirectedTo: "/login" };
  }
  return { allowed: target };
}

console.log(guard(false, "/users/42"));
console.log(guard(true, "/users/42"));
console.log(guard(false, "/login"));

Output:

{ redirectedTo: '/login' }
{ allowed: '/users/42' }
{ allowed: '/login' }

An unauthenticated request for /users/42 is redirected to /login; an authenticated one is allowed through; and an unauthenticated request for /login itself is allowed, so the guard does not bounce the visitor in an endless loop. In a component this runs inside an effect that calls navigate("/login") -- never during render, or the redirect fires on every pass. The guard stays a plain function of its inputs, which is exactly why it is easy to test.

Real World Example: A Route Table Where Order Would Have Bitten

An app has a home page, a "create user" page at /users/new, user profiles at /users/:id, and a NotFound. The danger is that /users/new also matches the dynamic /users/:id pattern -- with id captured as the literal string "new". Whether that is a bug depends entirely on how matching resolves. The model contrasts specificity ranking with a hand-rolled first-match resolver, the kind a switch statement or a React Router v5 mindset produces.

// Naive: take the FIRST route that matches, in source order.
function resolveFirst(routes, pathname) {
  for (let i = 0; i < routes.length; i++) {
    if (matchRoute(routes[i].pattern, pathname) !== null) return routes[i].name;
  }
  return "NotFound";
}

const appRoutes = [
  { pattern: "/", name: "Home" },
  { pattern: "/users/:id", name: "UserProfile" },
  { pattern: "/users/new", name: "NewUser" },
  { pattern: "*", name: "NotFound" }
];

console.log("v6 ranked:");
console.log("/users/new ->", resolve(appRoutes, "/users/new"));
console.log("/users/42  ->", resolve(appRoutes, "/users/42"));
console.log("naive first-match:");
console.log("/users/new ->", resolveFirst(appRoutes, "/users/new"));
console.log("/users/42  ->", resolveFirst(appRoutes, "/users/42"));

Output:

v6 ranked:
/users/new -> NewUser
/users/42  -> UserProfile
naive first-match:
/users/new -> UserProfile
/users/42  -> UserProfile

The ranked resolver sends /users/new to NewUser because the static route scores higher, and /users/42 to UserProfile. The naive resolver walks the list in order, and since /users/:id is written before /users/new, it grabs /users/new first and renders UserProfile with id === "new" -- the create-user page is unreachable and the profile page gets a nonsense id. Two identical route tables, opposite behaviour, decided purely by whether matching ranks or takes-the-first.

React Router v6 uses the ranked strategy, so the exact route is safe regardless of source order. But the model also exposes the limits you still own. The :id route matches /users/anything, so UserProfile must validate its param -- reject a non-numeric id -- rather than assume it. Two genuinely equal-specificity routes that overlap remain ambiguous no matter how they are ordered. And the whole thing depends on that trailing "*": the real design flaw to guard against is shipping the table without it, so an unmatched URL like /typo falls through to "NotFound" in this model but renders a blank screen in a real app that forgot the catch-all route.

Common Mistakes

  1. Using <a href> for internal links. A plain anchor triggers a full server reload, discarding all in-memory app state. Use <Link> or <NavLink> so navigation stays client-side.
  1. Assuming source order decides matches. React Router v6 ranks by specificity, but a hand-rolled first-match resolver lets /users/:id shadow /users/new. Express intent in the patterns, not the ordering.
  1. Omitting the catch-all * route. With no fallback, an unknown URL matches nothing and renders a blank screen instead of a clear NotFound page.
  1. Trusting a param's type. useParams values are always strings that matched anything in that slot; a :id route accepts /users/banana, so validate before using it.
  1. Nesting routes without an <Outlet>. A parent route that renders no <Outlet> never shows its child routes, so nested pages silently disappear.
  1. Calling router hooks outside a Router. useParams, useNavigate, and useLocation only work inside a <BrowserRouter>; used above it they throw or return nothing.
  1. Hard-coding link URLs that drift from the patterns. Hand-built strings like "/users/" + id fall out of sync when a route changes; derive link targets from the same source as the routes.
  1. Navigating during render. Calling the function from useNavigate() in the render body causes navigation loops; navigate inside an event handler or an effect.
  1. Forgetting the index route. A layout route with children but no index renders nothing at the parent's exact path, leaving it blank until a child path is visited.

Best Practices

  • Use <Link> and <NavLink> for in-app navigation and reserve <a href> for links that genuinely leave the app.
  • Always include a catch-all * route that renders a clear NotFound view.
  • Treat useParams values as untrusted strings: validate and coerce them before use.
  • Let React Router rank routes by specificity instead of reordering the list to force a match.
  • Keep route definitions in one place and derive link targets from them so URLs and patterns cannot drift apart.
  • Use nested routes with <Outlet> for shared layouts rather than repeating navigation chrome in every page.
  • Perform navigation in event handlers or effects with useNavigate, never during render.
  • Use useSearchParams for query-string state instead of parsing location.search by hand.

Practice Exercises

  1. Run matchRoute for ("/users/:id", "/users/42"), ("/users/:id", "/users/42/edit"), and ("/about", "/about"). Give each result and name the params extracted.
  1. Compute score for /users/new, /users/:id, and /*, then use resolve to say which view renders for /users/new and explain why the static route wins even though :id is listed first.
  1. Run resolve and resolveFirst for /users/new and explain, in terms of ranking versus source order, why they disagree and which is the bug.
  1. Add a /posts/:cat/:slug route to the table, trace the params for /posts/js/hooks, and describe what resolve returns for /unknown -- and what a real app would show if the * route were missing.