Appearance
6.4.9 — Routing with React Router
A shop has many pages: the home page, the list of products, one product's page, the checkout, a thank-you page. A customer expects the address bar to change as they move. They expect the Back button to work. They expect to copy a link to one product and send it to a friend.
A React app is one HTML page. The browser loads it once. So who changes the address and decides which screen to show? A router. This page teaches React Router, the most widely used router, by building the shop's navigation step by step.
1. What a router does
A router connects two things:
- The URL in the address bar, such as
/products/p2. - The components on the screen, such as
<ProductPage />.
When the URL changes, the router works out which components match it and draws them. When the user clicks a link, the router changes the URL without reloading the page, then draws the new components. The browser never goes back to the server for a new HTML file. This is why it is called a single-page app.
The URL is also state. It records which page the user is on, which product, which filter. State that lives in the URL has three powers that state in useState does not have: it survives a reload, it can be shared as a link, and the Back button undoes it. Remember this. Page 6.4.6 said "if the user should be able to bookmark it, share it, or press Back to undo it, it belongs in the URL". This page shows how.
Three modes, and which one this page teaches
React Router version 8 can be used in three ways.
| Mode | What it gives you | Used when |
|---|---|---|
| Declarative | Match URLs to components, links, nested routes | A simple app |
| Data | Everything above, plus loaders (load data before drawing) and actions (handle form submits) | A client-side app with real data |
| Framework | Data mode plus a build tool and server rendering | A full-stack app (Chapter 6.5) |
This page teaches data mode, because it is the one that real client-side apps use, and it includes the other two's basics.
Install it:
bash
npm install react-router2. Step 1: the route table
A route says: "when the URL looks like this, draw that component". You write all the routes in one list.
tsx
// src/router.tsx
import { createBrowserRouter } from 'react-router'
import { RootLayout } from './pages/RootLayout'
import { HomePage } from './pages/HomePage'
import { ProductsPage } from './pages/ProductsPage'
import { ProductPage } from './pages/ProductPage'
export const router = createBrowserRouter([ // (1)
{
path: '/', // (2)
Component: RootLayout, // (3)
children: [ // (4)
{ index: true, Component: HomePage }, // (5)
{ path: 'products', Component: ProductsPage }, // (6)
{ path: 'products/:productId', Component: ProductPage }, // (7)
],
},
])createBrowserRoutertakes the list of routes and creates a router that uses the browser's address bar and history.path: '/'is the top route. It matches every URL.Componentis what to draw when this route matches. Here it is the shared layout: the header and the footer that appear on every page.childrenare routes inside this route. The URL/productsfirst matches/, then the childproducts.index: truemeans "the child to draw when the URL is exactly the parent's path". So/drawsHomePageinside the layout.path: 'products'matches/products.:productIdis a dynamic segment. The colon means "any text goes here, call itproductId". It matches/products/p1,/products/p2, and so on. It must not start with a slash, because it is relative to the parent.
Now give the router to React. In the file that starts the app:
tsx
// src/main.tsx
import { createRoot } from 'react-dom/client'
import { RouterProvider } from 'react-router/dom'
import { router } from './router'
createRoot(document.getElementById('root')!).render(<RouterProvider router={router} />)RouterProvider replaces <App />. It listens to the address bar and draws the matching routes. (The import is from react-router/dom, the browser version.)
The home page can be as small as you like for now:
tsx
// src/pages/HomePage.tsx
export function HomePage() {
return <h1>Welcome to the shop</h1>
}How a URL becomes a screen
The figure shows what happens for /products/p2.
The router reads the URL from left to right and finds the chain of routes that match: the layout, then the product route. It draws the outer one (RootLayout) and puts the inner one (ProductPage) at the spot where the layout says <Outlet />.
3. Step 2: layouts, Outlet, and links
A layout route is a route whose job is to draw something shared, and leave a hole for the child. The hole is <Outlet />.
tsx
// src/pages/RootLayout.tsx
import { NavLink, Outlet, useNavigation } from 'react-router'
export function RootLayout() {
const navigation = useNavigation() // (1)
return (
<>
<header>
<nav>
<NavLink to="/">Home</NavLink> {/* (2) */}
<NavLink to="/products">Products</NavLink>
<NavLink to="/checkout">Checkout</NavLink>
</nav>
{navigation.state === 'loading' && <p>Loading…</p>}
</header>
<main>
<Outlet /> {/* (3) */}
</main>
</>
)
}useNavigation()tells you whether the router is in the middle of a page change. Itsstateis'idle','loading'(waiting for a loader) or'submitting'(waiting for a form action). We use it to show a small "Loading…" note.NavLinkis a link that knows whether it is the current page. React Router adds the classactiveto it, so you can style the current tab. ANavLinkcounts as active for its own path and every path below it. So "Products" stays highlighted on/products/p2too, which is what you want in a menu. If you want a link to be active only on its exact path, add theendprop. The link to/is a special case that React Router already treats as exact. We checked: at/a, the/link is not active and the/alink is.<Outlet />is where the matching child route is drawn. On/products, it drawsProductsPage. On/, it drawsHomePage.
Link is not <a>
To move between pages inside your app, use <Link to="/products">, not a plain <a href="/products">.
An <a href> makes the browser load a new page from the server. Your whole app restarts, and all state in memory is lost. A Link looks the same, but when clicked it only changes the URL and tells the router to draw the new screen. The page never reloads and the state is kept. Use <a> only for links that leave your site.
4. Step 3: dynamic routes and useParams
The product page needs to know which product to show. The answer is in the URL, and it is called a param.
tsx
import { useParams } from 'react-router'
function ProductPage() {
const { productId } = useParams() // for /products/p2, productId is the string 'p2'
// …
}useParams() returns the dynamic parts of the URL as an object. Two things to remember. Every param is a string, even if it looks like a number, so /products/42 gives '42'. And its type is string | undefined, because TypeScript cannot know that your route really has that segment. Check it before using it.
In practice you will rarely call useParams for loading data. Loaders (next) receive the params directly.
5. Step 4: loaders, which fetch the data before the page draws
Remember the hand-written fetching from page 6.4.3: draw the component, run an effect, fetch, show a spinner, finally show the data. The page is always drawn empty first, and each component only starts loading after its parent has drawn. This delay is called a waterfall.
A loader is a function attached to a route. The router calls it as soon as navigation starts, waits for it, and only then draws the page with the data already in hand. No empty flash, no effect to write.
First, a small stand-in for your server API. We use a pretend one so the page is self-contained. In your project, each function would call fetch.
ts
// src/api.ts
export type Product = { id: string; name: string; priceCents: number }
const products: Product[] = [
{ id: 'p1', name: 'Red mug', priceCents: 1999 },
{ id: 'p2', name: 'Desk lamp', priceCents: 4500 },
{ id: 'p3', name: 'Notebook', priceCents: 650 },
]
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
export async function fetchProducts(query: string): Promise<Product[]> {
await pause(50)
return products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase()))
}
export async function fetchProduct(id: string): Promise<Product | undefined> {
await pause(50)
return products.find((p) => p.id === id)
}
export async function placeOrder(order: { name: string; email: string }): Promise<{ orderId: string }> {
await pause(50)
return { orderId: `o-${order.name.length}${order.email.length}` }
}Now the product page and its loader:
tsx
// src/pages/ProductPage.tsx
import { data, useLoaderData } from 'react-router'
import type { LoaderFunctionArgs } from 'react-router'
import { fetchProduct } from '../api'
export async function productLoader({ params }: LoaderFunctionArgs) { // (1)
if (!params.productId) throw data('Missing product id', { status: 400 })
const product = await fetchProduct(params.productId)
if (!product) throw data('No such product', { status: 404 }) // (2)
return product // (3)
}
export function ProductPage() {
const product = useLoaderData<typeof productLoader>() // (4)
return (
<article>
<h1>{product.name}</h1>
<p>${(product.priceCents / 100).toFixed(2)}</p>
</article>
)
}- A loader receives an object with
params(the dynamic parts of the URL) andrequest(the full request, including the URL's query string). - If there is no such product, we throw a response with the status 404.
data(...)makes one. Throwing sends the user to the error screen that we will set up in section 8, so this component never has to deal with "what if the product is missing". - Whatever the loader returns becomes the page's data.
useLoaderDatareads it. The<typeof productLoader>tells TypeScript the exact type, soproduct.nameis known to be a string with no extra work. When the component draws, the data is already here. There is no loading state to check.
Connect the loader to the route. Add one line to the route table:
tsx
// the product route, with its loader attached
{ path: 'products/:productId', Component: ProductPage, loader: productLoader },When the user clicks a link to /products/p2, this happens, in order:
- The router sees the URL change and finds the matching routes.
- It calls
productLoaderfor the product route. (If the layout had a loader too, both would run at the same time, not one after the other.) navigation.stateis'loading'while it waits. The old page stays on screen, and our layout shows "Loading…".- The loader returns. The router draws
ProductPagewith the data.
6. Step 5: filters and the URL
The product list should support a search. Where does the search text live? Not in useState. If it lives in the URL (/products?q=lamp), then a reload keeps it, a link shares it, and Back undoes it. The part of the URL after the ? is called the search params (or query string).
tsx
// src/pages/ProductsPage.tsx
import { Form, Link, useLoaderData, useSearchParams } from 'react-router'
import type { LoaderFunctionArgs } from 'react-router'
import { fetchProducts } from '../api'
export async function productsLoader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url) // (1)
const q = url.searchParams.get('q') ?? ''
const sort = url.searchParams.get('sort') === 'price' ? 'price' : 'name'
const products = await fetchProducts(q)
products.sort((a, b) => (sort === 'price' ? a.priceCents - b.priceCents : a.name.localeCompare(b.name)))
return { products, q, sort }
}
export function ProductsPage() {
const { products, q, sort } = useLoaderData<typeof productsLoader>()
const [searchParams, setSearchParams] = useSearchParams() // (2)
function toggleSort() {
const next = new URLSearchParams(searchParams)
next.set('sort', sort === 'price' ? 'name' : 'price')
setSearchParams(next) // (3)
}
return (
<>
<Form method="get"> {/* (4) */}
<input name="q" defaultValue={q} placeholder="Search products" />
<button type="submit">Search</button>
</Form>
<button onClick={toggleSort}>Sort by {sort === 'price' ? 'name' : 'price'}</button>
<ul>
{products.map((p) => (
<li key={p.id}>
<Link to={`/products/${p.id}`}>{p.name}</Link> {/* (5) */}
</li>
))}
</ul>
</>
)
}- The loader reads the query string from the request's URL. A request URL is a normal
URLobject, sosearchParams.get('q')gives the text afterq=, ornullif absent. useSearchParamsworks likeuseState: it returns the current params and a function that changes them. But the "state" is the URL.- Changing the search params navigates to the new URL, and the router runs the loader again. The list updates, with no extra code of ours. We copy the old params first so the
qis kept when onlysortchanges. <Form method="get">submits to the same route with the field values in the URL (/products?q=lamp). The router intercepts it (no page reload) and runs the loader again. The text box usesdefaultValue, notvalue, because the URL is the source of truth, not React state.- Every product links to its own page. The link is the product's address.
We ran this against a real router: visiting /products?q=lamp&sort=price produced only "Desk lamp", and the URL stayed in the address bar for sharing.
7. Step 6: forms and actions
A loader reads. An action writes. It is a function attached to a route that runs when a <Form> is submitted with the method post, put or delete. It is the router's version of the submit handler you wrote by hand on page 6.4.3.
tsx
// src/pages/CheckoutPage.tsx
import { Form, redirect, useActionData, useNavigation } from 'react-router'
import type { ActionFunctionArgs } from 'react-router'
import { placeOrder } from '../api'
export async function checkoutAction({ request }: ActionFunctionArgs) {
const form = await request.formData() // (1)
const name = String(form.get('name') ?? '').trim()
const email = String(form.get('email') ?? '').trim()
if (name === '' || !email.includes('@')) {
return { error: 'Please enter your name and a valid email.' } // (2)
}
const { orderId } = await placeOrder({ name, email })
return redirect(`/thanks/${orderId}`) // (3)
}
export function CheckoutPage() {
const result = useActionData<typeof checkoutAction>() // (4)
const navigation = useNavigation()
const sending = navigation.state === 'submitting' // (5)
return (
<Form method="post"> {/* (6) */}
<label>
Name
<input name="name" />
</label>
<label>
Email
<input name="email" type="email" />
</label>
{result?.error && <p role="alert">{result.error}</p>}
<button type="submit" disabled={sending}>
{sending ? 'Placing order…' : 'Place order'}
</button>
</Form>
)
}- The action gets the request.
request.formData()reads the fields the user typed. This is the browser's ownFormDatatype, so you read each field by itsnameattribute. - If the data is bad, we return an object. The router stores it and the component can read it with
useActionData. The page is not left. - If all is well, we place the order and redirect to the thank-you page. A redirect is the standard way to finish a successful form: it moves the user on, and the Back button does not resubmit the order.
useActionDatareturns whatever the action returned last time, orundefinedbefore the first submit.- While the action runs,
navigation.stateis'submitting'. We disable the button, so a double-click cannot place two orders. <Form method="post">is the router's version of<form>. It does not reload the page. It calls the route's action.
Add action: checkoutAction to the route, the same way as loader:
tsx
{ path: 'checkout', Component: CheckoutPage, action: checkoutAction },The action sends the customer to /thanks/o-..., so that URL needs a page. It reads the order number from the URL with useParams, which is the first time we use it for real:
tsx
// src/pages/ThanksPage.tsx
import { useParams } from 'react-router'
export function ThanksPage() {
const { orderId } = useParams()
return <h1>Thank you! Your order number is {orderId}.</h1>
}Its route is { path: 'thanks/:orderId', Component: ThanksPage }, which you will see in the full table in section 8.
Notice what disappeared compared with the form on page 6.4.3: no useState for each field, no handleChange, no preventDefault. The browser keeps the field values, and the action reads them all at once. This is the simplest form style when you do not need to react while the user types. For forms that validate live, page 6.4.14 is better.
8. Step 7: errors and the 404 page
Things go wrong: the product does not exist, the server fails, a bug throws. Without a plan, the user sees a blank page or a crash. React Router lets every route have an error element, which is drawn instead of the route when anything inside it throws, whether in a loader, an action or a component.
tsx
// src/pages/ErrorPage.tsx
import { isRouteErrorResponse, Link, useRouteError } from 'react-router'
export function ErrorPage() {
const error = useRouteError() // (1)
if (isRouteErrorResponse(error)) { // (2)
return (
<section>
<h1>{error.status === 404 ? 'We could not find that' : `Error ${error.status}`}</h1>
<p>{String(error.data)}</p>
<Link to="/">Back to the shop</Link>
</section>
)
}
return (
<section>
<h1>Something went wrong</h1>
<p>{error instanceof Error ? error.message : 'Unknown error'}</p>
</section>
)
}useRouteErrorreturns whatever was thrown.isRouteErrorResponsechecks whether it is a response thrown withdata(...), which carries astatus(such as 404) anddata(the message). If it is, we show a friendly page. Otherwise it is an ordinary error, like a bug.
Attach it to a route with ErrorBoundary: ErrorPage. An error goes to the closest error page above the place where it was thrown. So put one on the top route as a safety net, and more on routes where you want the rest of the screen to survive:
tsx
// src/router.tsx
import { createBrowserRouter } from 'react-router'
import { RootLayout } from './pages/RootLayout'
import { HomePage } from './pages/HomePage'
import { ProductsPage, productsLoader } from './pages/ProductsPage'
import { ProductPage, productLoader } from './pages/ProductPage'
import { CheckoutPage, checkoutAction } from './pages/CheckoutPage'
import { ThanksPage } from './pages/ThanksPage'
import { ErrorPage } from './pages/ErrorPage'
import { NotFoundPage } from './pages/NotFoundPage'
export const router = createBrowserRouter([
{
path: '/',
Component: RootLayout,
ErrorBoundary: ErrorPage, // (1)
HydrateFallback: () => <p>Loading the shop…</p>, // (4)
children: [
{ index: true, Component: HomePage },
{ path: 'products', Component: ProductsPage, loader: productsLoader },
{
path: 'products/:productId',
Component: ProductPage,
loader: productLoader,
ErrorBoundary: ErrorPage, // (2)
},
{ path: 'checkout', Component: CheckoutPage, action: checkoutAction },
{ path: 'thanks/:orderId', Component: ThanksPage },
{ path: '*', Component: NotFoundPage }, // (3)
],
},
])- The safety net. An error anywhere below, with no closer error page, replaces the whole screen with this one, header included.
- A closer error page. A missing product replaces only the product part of the screen. The layout, with its header and menu, stays. Put these where you want the damage to stay small.
path: '*'is the catch-all. It matches any URL that nothing else matched, so/blahshows your own "page not found" screen.HydrateFallbackis what to draw while the very first page's loaders are running. On later navigations the old page stays on screen, but on the first visit there is no old page. Without this, React Router prints a warning and shows nothing until the data arrives. We saw that warning.
The catch-all page is only a few lines:
tsx
// src/pages/NotFoundPage.tsx
import { Link } from 'react-router'
export function NotFoundPage() {
return (
<section>
<h1>Page not found</h1>
<Link to="/products">See all products</Link>
</section>
)
}We tested the product route with an unknown id: the loader threw the 404, and the error page showed "We could not find that: No such product" inside the layout.
9. Step 8: moving the user yourself
Sometimes your code, not a click, must send the user somewhere.
After an event, in a component: useNavigate.
tsx
import { useNavigate } from 'react-router'
function BackToShopButton() {
const navigate = useNavigate()
return <button onClick={() => navigate('/products')}>Keep shopping</button>
}Before a page draws, in a loader or action: redirect. This is how you protect a page for logged-in users only.
tsx
import { redirect } from 'react-router'
function isLoggedIn(): boolean {
return localStorage.getItem('token') !== null
}
export async function accountLoader() {
if (!isLoggedIn()) throw redirect('/login') // (1)
return { email: 'ana@example.com' }
}- If there is no token, the user is sent to
/loginand the account page never draws. The check happens before any of the page's code runs, so there is no flash of private content. Remember, though, that this is only a convenience for the user. The real protection of private data is on the server, which must check the token again on every request (Chapter 8).
A fixed redirect: <Navigate to="/products" replace /> as an element, for example on an old URL that moved. replace swaps the current history entry instead of adding one, so Back does not bounce the user back into the redirect.
10. Loading pages only when needed
By default all route components are put in one JavaScript file that the user downloads at the start. A big admin area that most customers never open should not be in it. A route can load its code on demand:
tsx
{
path: 'admin',
lazy: async () => { // (1)
const { AdminPage, adminLoader } = await import('./pages/AdminPage')
return { Component: AdminPage, loader: adminLoader }
},
},lazyis a function that returns the route's pieces. Theimport()makes the bundler putAdminPagein a separate file that is only downloaded when the user first visits/admin.
11. Where this fits
- Navigation and URL state: the router.
- Data from a server: loaders work, but they do not cache or refresh. Many teams use a loader to start the request and TanStack Query to own the data (page 6.4.10).
- Typed routes: React Router does not check at compile time that
/products/${id}is a real route, and its search params are plain strings you parse yourself. TanStack Router (page 6.4.12) is built around type safety. If your project values that, learn it next. - A full-stack app with server rendering: Chapter 6.5.
What the interviewer will push on
"How does client-side routing work?" The router keeps the current URL in sync with the browser's History API (pushState). A click on a Link changes the URL and tells React to draw the matching components. No page request goes to the server. Say the cost: your server must send the same HTML for every path, or a reload on /products/p2 returns a 404.
"Link vs <a>?" <a> reloads the page from the server and loses in-memory state. Link changes the URL and re-draws without a reload.
"What are nested routes and Outlet?" Routes inside routes, matching nested URL segments, with each parent drawing a layout and <Outlet /> marking where the child goes. Shared headers and side menus are written once.
"What is a loader, and why not useEffect?" A function the router runs when navigation starts, before the page draws. It avoids the empty-then-fill flash and the waterfall of nested effects, and the router gives you pending states and error handling for free. Add that it does not cache, so many teams combine it with TanStack Query.
"How do you protect a route?" A loader that throws redirect('/login') when there is no session. Then volunteer that it is a user-experience feature only, and that the server must verify every request.
"Where does filter state belong?" In the URL search params, so it can be bookmarked, shared and undone with Back. This answer links back to the state-management discussion and shows you choose the right home for state.
"How do you handle 404 and errors?" A * route for unknown URLs, ErrorBoundary on routes, and loaders that throw data(..., { status: 404 }) for missing records.
One thing to volunteer: point out that a single-page app needs the server configured to return the app's HTML for every path ("history fallback"), or refreshing a deep link will fail.
Recall
- A router maps the URL to components and changes the URL without reloading. The URL is state: it survives reload, can be shared, and Back undoes it.
- Data mode:
createBrowserRouter([...routes])plus<RouterProvider router={router} />(import fromreact-router/dom). - A route has
path,Component, optionalchildren,loader,action,ErrorBoundary,lazy.index: trueis the child drawn at the parent's exact path.path: '*'is the catch-all.:nameis a dynamic segment. - A layout route draws shared UI plus
<Outlet />, where the matching child appears. LinkandNavLinknavigate without reload.NavLinkadds the classactivefor its path and below.endmakes it exact (the/link is already exact). A plain<a>reloads the page.useParams()gives dynamic parts. All values are strings and may beundefined.- A loader runs before the page draws, receives
{ params, request }, returns the data.useLoaderData<typeof loader>()reads it. If it throws a response, the error element draws. Loaders of nested routes run in parallel. - An action runs on
<Form method="post">.request.formData()reads the fields. Return data (for errors, read withuseActionData) orredirect(...)after success.useNavigation().stateis'idle','loading'or'submitting'. - Search params (
?q=lamp) hold filters. Read withnew URL(request.url).searchParamsin a loader oruseSearchParams()in a component. A<Form method="get">updates them. - Errors:
ErrorBoundary+useRouteError()+isRouteErrorResponse(); throwdata('msg', { status: 404 })from loaders. - Redirect users:
useNavigate()in event handlers,throw redirect('/login')in loaders. Real protection is on the server. lazy: () => import(...)loads a route's code only when visited.
Self-test: What does <Outlet /> do? · When is a NavLink active, and what does end change? · When is a loader called compared with the component, and what does that remove? · Why is the search text kept in the URL instead of useState? · How does an action tell the page about a validation error, and how does it finish a successful submit?
Next: 6.4.10 teaches TanStack Query, which does the part that loaders leave undone: it remembers server data, shares it between screens, and refreshes it for you.