Skip to content

React Router

React Router enables client-side navigation in single-page applications. URLs change, history updates, and React renders the matching route component — without full page reloads.

Routing in SPAs

Install react-router-dom and wrap your app in <BrowserRouter>. Define routes with <Routes> and <Route path element />>. Use <Link> and useNavigate() for navigation.

React Router v6 simplified the API: relative routes, nested layouts, and loaders/actions in v6.4+ data APIs. This course covers the patterns used in most production apps.

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

function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link><Link to="/about">About</Link></nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

BrowserRouter uses HTML5 history API for clean URLs without #.

Core React Router Components

<BrowserRouter>   // history context
<Routes>          // route matching container
<Route path element />  // path → component
<Link to="..." />       // declarative navigation
<Outlet />              // nested child routes render here
  • Install react-router-dom, not react-router alone for web.
  • Configure SPA fallback on static hosts for deep links.
  • Use Link instead of <a href> for internal routes.
  • Vite dev server handles SPA routing; production needs server config.

React Router Essentials

Most-used APIs in React Router v6.

API Purpose
BrowserRouter Wrap app for web routing
Routes / Route Declare path → element mapping
Link Navigate without reload
useNavigate Imperative navigation
useParams Read URL parameters
Outlet Render nested routes

React Router v6 vs v7

React Router v7 builds on v6 with framework features closer to Remix. Existing v6 apps migrate incrementally. Core Routes/Route/Link patterns remain familiar.

Vite + Production SPA Routing

Static hosts must serve index.html for unknown paths so React Router can handle /about on direct load. Configure redirects on Netlify, Vercel, or nginx accordingly.

Common Mistakes

  • Using <a href> for internal links causing full page reloads.
  • Forgetting SPA fallback in production deployments.
  • Not wrapping app in Router at all.
  • Mixing v5 and v6 API patterns from old tutorials.

Key Takeaways

  • React Router maps URLs to components in SPAs.
  • Use BrowserRouter, Routes, Route, and Link.
  • Configure server fallback for client-side routes in production.
  • v6 API is simpler — avoid outdated v5 examples.

Pro Tip

Create a src/routes.jsx module exporting your route tree — keeps App.jsx clean as routes grow.