Routing with React Router
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 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
npm install react-routerReact 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.)
// 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.
Links
Use <Link> for internal navigation, not <a href>:
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 for menus
<NavLink> knows whether it matches the current URL. It adds an active class automatically, and aria-current="page" for screen readers:
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:
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:
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.
Navigating from code
After a form submission or a login, navigate programmatically with useNavigate:
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.
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).
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 hereimport { createBrowserRouter, Link, NavLink, Outlet, 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' },
];
function Layout() {
return (
<>
<nav>
<NavLink to="/" end>Home</NavLink> <NavLink to="/courses">Courses</NavLink>
</nav>
<Outlet />
</>
);
}
function Home() {
return <h1>Welcome to the Academy</h1>;
}
function Courses() {
const [searchParams, setSearchParams] = useSearchParams();
const level = searchParams.get('level') ?? 'all';
const visible = level === 'all' ? courses : courses.filter((c) => c.level === level);
return (
<>
<h1>Courses</h1>
<select
aria-label="Level"
value={level}
onChange={(e) =>
setSearchParams(e.target.value === 'all' ? {} : { level: e.target.value })
}
>
<option value="all">All</option>
<option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option>
</select>
<ul>
{visible.map((c) => (
<li key={c.slug}>
<Link to={`/courses/${c.slug}`}>{c.title}</Link>
</li>
))}
</ul>
</>
);
}
function CoursePage() {
const { slug } = useParams();
const course = courses.find((c) => c.slug === slug);
if (!course) return <h1>Course not found</h1>;
return <h1>{course.title}</h1>;
}
function NotFound() {
return <h1>Page not found</h1>;
}
export const routes = [
{
path: '/',
Component: Layout,
children: [
{ index: true, Component: Home },
{ path: 'courses', Component: Courses },
{ path: 'courses/:slug', Component: CoursePage },
{ path: '*', Component: NotFound },
],
},
];
const router = createBrowserRouter(routes);
export default function App() {
return <RouterProvider router={router} />;
}Summary
- Client-side routing changes the URL and the rendered components without reloading the page.
- Configure routes with
createBrowserRouter([...])and render them with<RouterProvider>fromreact-router/dom. - Use
<Link to>and<NavLink>instead of<a href>for internal links; NavLink knows when it’s active. - Dynamic segments like
/courses/:slugare read withuseParams(); query strings withuseSearchParams(). - Navigate from code with
useNavigate(), and add a*route for 404 pages.