Routing With React Router: One Page, Many Addresses
A task app with five routes: how the router picks the best match, why Link makes zero requests while a plain a tag downloads the app again, the Outlet slot, the useParams string trap (TS2367), useNavigate after a save, a not-found page and the 404 on refresh.
What you will learn
- Explain why a single-page app loads one index.html for every address
- Write a route table and predict which route matches a URL
- Use Link, Outlet, useParams and useNavigate, and avoid the string id bug
- Add a not-found route and make the host serve index.html on refresh
Before you start
- React components, props and state
- React 19 form actions (for the save example)
On a normal website, clicking a link sends the browser to the server for a new page, and everything starts again. A single-page app works differently. The browser asks for / once, gets one HTML page plus the JavaScript, and from then on the address bar changes without any new page being requested. Only part of the screen is redrawn.
React Router is what maps those addresses to components. This article follows a small task app with five routes, using the outputs from the lecture's scripts and a real Chrome session.
One HTML file for every page
The app has one index.html with an empty <div id="root"> and a script tag for main.tsx. npm run build writes exactly one HTML file, one JavaScript file and one CSS file:
dist/index.html 0.40 kB │ gzip: 0.27 kB
dist/assets/index-CKRgU76b.css 0.76 kB │ gzip: 0.39 kB
dist/assets/index-BkWeoiI8.js 315.91 kB │ gzip: 99.56 kB
So /, /tasks and /tasks/2 all get the same page, and JavaScript draws the right screen into the root.
The route table
import type { RouteObject } from 'react-router'
import Layout from './Layout'
import Tasks from './Tasks'
import TaskDetail from './TaskDetail'
import NewTask from './NewTask'
import NotFound from './NotFound'
// The route table: a URL path -> the component.
// Children are drawn inside Layout's <Outlet />.
export const routes: RouteObject[] = [
{
path: '/',
element: <Layout />,
children: [
{ index: true, element: <h3>Welcome</h3> },
{ path: 'tasks', element: <Tasks /> },
{ path: 'tasks/:id', element: <TaskDetail /> },
{ path: 'tasks/new', element: <NewTask /> },
{ path: '*', element: <NotFound /> },
],
},
]
Routes are plain data: a path and the element to show. The parent at / draws Layout for every path, and its children are drawn inside Layout's Outlet. Two special paths: :id is a placeholder that matches any one part of the URL, and * matches anything no other route matches.
How the router matches a URL
/ -> index <h3> {}
/tasks -> tasks Tasks {}
/tasks/2 -> tasks/:id TaskDetail {"id":"2"}
/tasks/new -> tasks/new NewTask {}
/oops -> * NotFound {"*":"oops"}
/tasks/new fits two routes: tasks/:id (with id "new") and tasks/new word for word. The first one in the list doesn't win; the more exact one does. A fixed word beats :id, and :id beats *. Note that the id in {"id":"2"} is text.
The router reads the address bar
import { createRoot } from 'react-dom/client'
import { createBrowserRouter } from 'react-router'
import { RouterProvider } from 'react-router/dom'
import { routes } from './routes'
import './index.css'
// Reads the address bar and keeps it in sync
const router = createBrowserRouter(routes)
createRoot(document.getElementById('root')!).render(
<RouterProvider router={router} />,
)
createBrowserRouter takes the routes and reads the address bar. RouterProvider draws the match and keeps listening: a new URL means a new match and a new render.
Link and the Outlet
import { Link, Outlet } from 'react-router'
// The shared frame. Only the Outlet changes.
export default function Layout() {
return (
<>
<nav className="nav">
<b>Team tasks</b>
<Link to="/">Home</Link>
<Link to="/tasks">Tasks</Link>
<Link to="/tasks/new">New task</Link>
</nav>
<main className="page">
<Outlet />
</main>
</>
)
}
A Link renders a normal <a href="/tasks">. On a click it calls preventDefault(), so the browser doesn't go to the server, then writes the new URL with history.pushState. The router sees it, matches, and redraws the Outlet:
/ -> Outlet: Welcome
click "Tasks": default prevented = true
history.pushState("/tasks")
/tasks -> Outlet: Tasks
click "Email Jack": default prevented = true
history.pushState("/tasks/2")
/tasks/2 -> Outlet: Email Jack | Owner: Noah
nav is the same element: true
The last line matters: the nav is the same element before and after. Only the Outlet changed.
Link or a plain <a>?
The lecture compares both in a real Chrome window, putting a small note on window before each click to see whether the page survives:
| Step | Requests | Window note |
|---|---|---|
Open / | 1 document, 21 in total | (not set yet) |
Link to /tasks | 0 | kept |
Plain <a href> to /tasks/2 | 1 document, 20 in total | gone |
A plain <a> works, but every click downloads and starts the whole app again and loses everything in memory. Inside your app, use Link. For another site, use a plain <a href>.
Links built from data
import { Link } from 'react-router'
import { tasks } from './data'
export default function Tasks() {
return (
<div className="card">
<h3>Tasks</h3>
<ul>
{tasks.map((t) => (
<li key={t.id}>
<Link to={`/tasks/${t.id}`}>
{t.title}
</Link>
</li>
))}
</ul>
</div>
)
}
A template string builds each address from the task id: id 2 gives /tasks/2.
useParams: the URL as data
import { Link, useParams } from 'react-router'
import { tasks } from './data'
export default function TaskDetail() {
const { id } = useParams() // always a string
const task = tasks.find((t) => t.id === Number(id))
if (!task) return <p>No task with id {id}</p>
return (
<div className="card">
<h3>{task.title}</h3>
<p>Owner: {task.owner}</p>
<Link to="/tasks">Back to tasks</Link>
</div>
)
}
useParams(): {"id":"2"}
typeof params.id: string
Number(params.id): 2
/tasks/2 -> Outlet: Email Jack | Owner: Noah
/tasks/9 -> Outlet: No task with id 9
useParams() gives the :id part as a string, text from the URL. The ids in data.ts are numbers, so line 6 converts with Number(id) before comparing. An id that doesn't exist, like 9, shows a message instead of crashing.
A number is not a string
Forget Number and write t.id === id. A number is never === a string, so find gives undefined, and the page says "No task with id 2" for a task that exists:
/tasks/2 -> Outlet: No task with id 2
/tasks/9 -> Outlet: No task with id 9
TypeScript catches it before it runs:
src/TaskDetail.tsx(6,34): error TS2367: This comparison appears to be unintentional because the types 'number' and 'string | undefined' have no overlap.
useNavigate after an action
import { useNavigate } from 'react-router'
import { addTask } from './data'
export default function NewTask() {
const navigate = useNavigate()
function save(form: FormData) {
const task = addTask(String(form.get('title')))
// done: send the user to the new task's page
navigate(`/tasks/${task.id}`)
}
return (
<form className="card" action={save}>
<h3>New task</h3>
<input name="title" placeholder="Title" />
<button>Save</button>
</form>
)
}
Sometimes you move the user from code, for example after saving a form. The form action adds the task (id 4) and calls navigate, which does the same pushState a Link does:
/tasks/new -> Outlet: New task
click "Save"
history.pushState("/tasks/4")
/tasks/4 -> Outlet: Call Olivia | Owner: Olivia
The not-found route
import { Link, useLocation } from 'react-router'
// '*' matches any URL no other route matches
export default function NotFound() {
const { pathname } = useLocation()
return (
<div className="card">
<h3>Page not found</h3>
<p>Nothing lives at {pathname}</p>
<Link to="/">Go home</Link>
</div>
)
}
/oops -> Outlet: Page not found | Nothing lives at /oops
nav links: Home | Tasks | New task
path: '*' catches every unknown URL, and because it is a child of Layout, the nav is still there. useLocation gives the current path for the message. A typo shows a page, not a blank screen.
A refresh on a deep URL
Press F5 on /tasks/2 and the browser really does ask the server for /tasks/2. There is no such file. The lecture asks two servers for both paths:
http://localhost:5173
GET / -> 200 index.html
GET /tasks/2 -> 200 index.html
http://localhost:8000
GET / -> 200 index.html
GET /tasks/2 -> 404 not the app
The Vite dev server (port 5173) knows this is a single-page app and sends index.html; the app starts, the router reads /tasks/2 and draws Email Jack again. A plain file server (port 8000) answers 404. When you host the app, the host must answer every app path with index.html.
Recap
| Piece | What it does |
|---|---|
index.html | One page for every address; JavaScript draws into root |
| Route table | Path to element; the most exact match wins, * only as a last resort |
Link | preventDefault + pushState: no request, state kept |
Outlet | The slot in the layout that the child route fills |
useParams | URL params as strings; convert with Number |
useNavigate | Move the user from code, for example after a save |
| Hosting | Serve index.html for every app path |
Try it yourself: add a route tasks/:id/edit with its own component, and work out which route /tasks/2/edit matches before you click. The next step for this app is real data from a server, covered in server state with TanStack Query.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
