React Router Fundamentals: Routes, Links, and Params

Learn how React Router matches URLs to screens, navigates with links, reads dynamic parameters, and organizes shared layouts and route loading states.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

React Router maps URL patterns to React screens and handles in-app navigation. This guide walks through route links, dynamic parameters, nested layouts, and the choice between screen-level and route-level loading or error handling. It also covers direct URL refreshes, parameter validation, and server-side authorization so readers can build routes that behave well in real deployments.

React Router Fundamentals: Routes, Links, and Params

Introduction

A client side router maps URL patterns to components and handles in-app navigation without reloading the document for every click. URLs still matter: people can bookmark screens or open them directly.

The example uses React Router’s declarative route components. APIs depend on the mode you choose.

This guide covers path matching, links, dynamic parameters, and the role of shared layouts and route states.

Match paths to components

A route pairs a path pattern with a screen. A dynamic segment such as :productId becomes a string parameter. Use Link for navigation handled by the router:

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

function ProductPage() {
  const { productId } = useParams();
  return <h1>Product {productId}</h1>;
}

export function App() {
  return (
    <BrowserRouter>
      <Link to="/products/42">View product 42</Link>
      <Routes>
        <Route path="/products/:productId" element={<ProductPage />} />
      </Routes>
    </BrowserRouter>
  );
}

The parameter may be missing, so validate it before using it in a request. The router handles matching; your page still decides what to show while data loads or fails.

When to Use / When NOT to Use

Use router links within the app and normal <a href> links for other websites or downloads. Links work for keyboard and assistive technology users; avoid clickable <div> elements.

For a small app, a page component can render loading and error states while it fetches. Router modes with loaders and error boundaries can handle these at the route boundary. Choose based on request ownership and shared behavior; a simple request may not need router data APIs.

Use client-side routes when several screens share a React app and in-app navigation should preserve its shell. Do not add a router to a single static page with no distinct URLs; plain links may be enough.

flowchart LR
    A[User follows link] --> B[URL changes]
    B --> C[Router matches route]
    C --> D[Read route params]
    D --> E[Render page or nested layout]
    E --> F[Show loading, data, or error]

Trade-Off Table

Choice Use it when Trade-off
Router Link Moving between screens in the same app Needs the router context and route match
Anchor href Leaving the app or opening a file Usually triggers a full document navigation
Flat routes Screens have unrelated layouts Shared page structure may be repeated
Nested routes Child screens share a layout Route tree takes a little planning

Production Failure Scenarios

A route may work after in-app navigation but fail when reloaded at /products/42. The host looks for a physical file and returns 404 before React starts. Configure hosting to serve the app entry point for client routes, and keep a not-found screen for unmatched paths.

A malformed productId can reach a request and produce a confusing error page. Validate the parameter before fetching, then show an invalid-ID or not-found state instead of treating it as a server outage.

Security and Compliance Notes

Treat path parameters as untrusted input. A route parameter is not proof that a user may view or edit that resource. Validate its format, then enforce access on the server. Do not place secrets or authorization decisions in client route logic.

Observability Checklist

  • Record route changes and request IDs for route data requests.
  • Track loading failures and unmatched paths.
  • Keep tokens and private record contents out of logs.

Common Pitfalls / Anti-Patterns

  • Using a clickable element instead of a link for navigation.
  • Assuming a route parameter is a validated number or permission check.
  • Forgetting host fallback rules for direct visits to client-side routes.

Quick Recap Checklist

  • Map URL patterns to page components.
  • Use router links within the app and anchors outside it.
  • Treat route parameters as optional strings that need validation.
  • Use nested routes for screens with a shared layout.
  • Decide where loading and error UI belongs based on request ownership.
  • Configure hosting for direct visits to client routes.

Interview Questions

1. What does client side routing do?
It matches the current URL to a React screen and updates the view during in-app navigation without requesting a new document for every route.
2. What does a dynamic route segment provide?
A segment such as :productId captures part of the URL. Router APIs expose that captured value as a string parameter to the matched screen.
3. Why can a nested route use an outlet?
The outlet marks where a matched child screen appears inside its parent layout, so shared navigation or headings do not need to be repeated.
4. When should an app use Link instead of an anchor?
Use Link for navigation within the router-managed app.
  • Use an anchor for external sites or downloads.
  • Both provide native link semantics and keyboard behavior.
5. What type does a route parameter have?
It is a string that may be missing when no matching parameter is present.
  • Validate before converting it to a number.
  • Do not treat its format as authorization.
6. How does a nested route share layout?
The parent route renders shared markup and an Outlet for the child screen.
  • Child paths can remain relative to their parent route.
  • Shared headings and navigation do not need to be repeated.
7. Why might a route load in the app but fail on refresh?
The host may look for a physical file at the nested path.
  • Configure a fallback to the app entry point for client routes.
  • Test a direct browser visit to a nested URL.
8. Where should route loading UI live?
Put it with the part of the app that owns the request.
  • A simple screen can handle its own request state.
  • Route loaders and error boundaries may fit shared route data behavior.
9. Does a route parameter prove a user can access a record?
No. It only identifies part of the requested URL.
  • Enforce access on the server for protected resources.
  • Keep secrets out of client route code.
10. What should a not-found route handle?
It should give a useful result when no route matches the current URL.
  • Distinguish an unmatched route from a failed data request.
  • Offer a clear path back to a known screen.

Further Reading

Conclusion

When a URL changes, decide whether the screen shares data or layout with its parent, then place loading and error states with the request owner. Validate parameters and test direct visits so bookmarked routes behave like in-app navigation.

Category

Related Posts

Controlled Inputs and Forms in React

Learn to control form values with React state, type change and submit events, show validation feedback, and handle form data safely with TypeScript.

#react #typescript #forms

React Event Handling and Event Types

Learn to type React click, change, and form handlers in TypeScript, pass callbacks through props, and validate user input safely with clear examples.

#react #typescript #events

React Props, Children, and Component Composition

Learn to pass data and callbacks through React props, use children for flexible layouts, and compose small components without building giant prop APIs.

#react #typescript #components