Routing with React Router

Topic 1 of 3 in Routing8 min readIntermediateFree course

Overview

So far your app has had one screen. Real apps have many: a home page, a course catalogue, a page for each course, a profile. Each should have its own URL, so users can bookmark it, share it, refresh it and use the back button. React Router is the most widely used library for this.

Client-side routing

In a traditional multi-page site, clicking a link makes the browser request a new HTML page and the whole page reloads, losing state. In a React single-page app, clicking a Link makes the router update the URL with the history API, and only the matching components change. A route config maps the path /courses/:courseId to CoursePage, so /courses/react renders CoursePage with params.courseId equal to “react”.

In a single-page app (SPA), the browser loads your app once. After that, the router intercepts link clicks, updates the URL using the browser’s History API, and renders the components that match the new URL. No full page reload, so it’s fast and your app’s state (like a playing video or a shopping cart) survives navigation.

Setup

Terminal
npm install react-router

React Router 8 is a single package: import routing APIs from react-router, and the DOM renderer piece, RouterProvider, from react-router/dom. (Tutorials for older versions import from react-router-dom, which no longer exists in v8.)

JSX
// src/main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { createBrowserRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';
import Home from './pages/Home.jsx';
import Courses from './pages/Courses.jsx';
import CoursePage from './pages/CoursePage.jsx';
import NotFound from './pages/NotFound.jsx';

const router = createBrowserRouter([
  { path: '/', Component: Home },
  { path: '/courses', Component: Courses },
  { path: '/courses/:slug', Component: CoursePage },
  { path: '*', Component: NotFound },
]);

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <RouterProvider router={router} />
  </StrictMode>,
);

Each route object maps a path to a Component. React Router picks the best match for the current URL — specific paths like /courses/new beat dynamic ones like /courses/:slug regardless of order. The * route matches anything left over, making it your 404 page.

This “data mode” setup (createBrowserRouter) also unlocks loaders and actions, covered later in this chapter. React Router also has a simpler declarative mode (<BrowserRouter> with <Routes> and <Route> elements) and a full framework mode with server rendering — the concepts carry across all three.

Use <Link> for internal navigation, not <a href>:

JSX
import { Link } from 'react-router';

<Link to="/courses">Browse courses</Link>
<Link to={`/courses/${course.slug}`}>{course.title}</Link>

<Link> renders a real <a> (so it’s accessible, can be opened in a new tab, and works with right-click), but intercepts normal clicks to navigate without a reload. A plain <a href="/courses"> would reload the whole app.

<NavLink> knows whether it matches the current URL. It adds an active class automatically, and aria-current="page" for screen readers:

JSX
import { NavLink } from 'react-router';

<nav>
  <NavLink to="/" end>Home</NavLink>
  <NavLink to="/courses">Courses</NavLink>
  <NavLink to="/profile" className={({ isActive }) => (isActive ? 'tab tab-active' : 'tab')}>
    Profile
  </NavLink>
</nav>

end makes / match only exactly — otherwise “Home” would be active on every page, since every path starts with /.

URL parameters

A segment starting with : is a dynamic segment. Read its value with useParams:

JSX
import { useParams } from 'react-router';

function CoursePage() {
  const { slug } = useParams();          // /courses/react → slug === 'react'
  const course = courses.find((c) => c.slug === slug);

  if (!course) return <h1>Course not found</h1>;
  return <h1>{course.title}</h1>;
}

Parameters are always strings. Convert them if needed: Number(params.id). A route can have several: /courses/:slug/lessons/:lessonId. Add ? to make one optional: /:lang?/courses.

Search params

Query strings (/courses?level=beginner&page=2) are perfect for filters, sorting, tabs and pagination — state the user would expect to survive a refresh or a shared link. Read and write them with useSearchParams:

JSX
import { useSearchParams } from 'react-router';

function Courses() {
  const [searchParams, setSearchParams] = useSearchParams();
  const level = searchParams.get('level') ?? 'all';
  const page = Number(searchParams.get('page') ?? 1);

  return (
    <select
      value={level}
      onChange={(e) => setSearchParams({ level: e.target.value, page: '1' })}
    >
      …
    </select>
  );
}

searchParams is a standard URLSearchParams object. Setting it navigates to the new URL, and the back button steps through filter changes. Using the URL as state means you don’t need useState for those values at all.

After a form submission or a login, navigate programmatically with useNavigate:

JSX
import { useNavigate } from 'react-router';

function LoginForm() {
  const navigate = useNavigate();

  async function handleSubmit(e) {
    e.preventDefault();
    await logIn(new FormData(e.currentTarget));
    navigate('/dashboard');                    // push a new history entry
    // navigate('/dashboard', { replace: true }) — replace, so Back doesn't return to login
    // navigate(-1) — go back
  }
  // …
}

Prefer <Link> for anything the user clicks to go somewhere; use navigate for redirects that happen as a result of something. (Loaders and actions can also redirect, as you’ll see.)

Other useful hooks

Hook Returns
useLocation() the current location: pathname, search, hash, state
useParams() dynamic segment values
useSearchParams() query string, plus a setter
useNavigate() a function for programmatic navigation
useNavigation() whether a navigation is in progress (see Route loaders and actions)

Scroll restoration

SPAs don’t reset the scroll position automatically. Render <ScrollRestoration /> once in your root layout and React Router scrolls to the top on new pages and restores the position when going back.

Deploying an SPA with routes

Your server must return index.html for every path, so that refreshing /courses/react loads the app (which then shows the right page) instead of a server 404. Static hosts call this an “SPA fallback” or “rewrite” — see Deploying React apps.

URLs are part of your UI. Design them like you design screens: readable (/courses/react, not /c?id=7), stable, and containing the state users would want to share.

Exercise

Course pages with URLs

Set up React Router with routes for / (a Home page), /courses (a Courses list linking to each course), /courses/:slug (a CoursePage that reads slug with useParams and shows “Course not found” for unknown slugs) and a catch-all * route for a 404 page. Use NavLink for the main navigation so the active link gets an active class. In Courses, add a level filter stored in the URL search params (?level=beginner).

JavaScript
import { createBrowserRouter, Link, NavLink, useParams, useSearchParams } from 'react-router';
import { RouterProvider } from 'react-router/dom';

const courses = [
  { slug: 'react', title: 'React', level: 'intermediate' },
  { slug: 'html', title: 'HTML basics', level: 'beginner' },
];

// your code here

Summary

  • Client-side routing changes the URL and the rendered components without reloading the page.
  • Configure routes with createBrowserRouter([...]) and render them with <RouterProvider> from react-router/dom.
  • Use <Link to> and <NavLink> instead of <a href> for internal links; NavLink knows when it’s active.
  • Dynamic segments like /courses/:slug are read with useParams(); query strings with useSearchParams().
  • Navigate from code with useNavigate(), and add a * route for 404 pages.