Sub topic 1
How client-side routing works
A router connects the URL in the address bar to what the user sees. In a traditional website, the server does that work. In a single-page application (SPA), JavaScript running in the browser does it. This chapter explains the mechanism that React Router builds on, so that later chapters on route objects, loaders and actions make sense.
Prerequisites
This chapter assumes you know:
- JavaScript: ES modules,
async/await, andfetch. - React function components and JSX.
- Basic hooks such as
useStateanduseEffect. - The parts of a URL (origin, path, query string, hash) and that the browser keeps a back/forward history.
You do not need to know React Router yet. This chapter uses plain browser APIs.
Server-rendered navigation
On a classic multi-page site, clicking a link makes the browser do the following:
- Send a new HTTP request to the server for the target URL.
- Receive a complete HTML document.
- Discard the current page, including all JavaScript state, and render the new document.
Every navigation is a full page load. The server decides what each URL means. This model is simple and works well for content sites. It is a poor fit for apps with persistent UI such as a sidebar, a playing video, or a half-filled form, because each navigation resets them.
Client-side navigation
A single-page app loads one HTML document and one JavaScript bundle. After that, the URL changes without a new document request:
- The user clicks a link.
- JavaScript intercepts the click and stops the browser's default navigation.
- JavaScript updates the address bar to the new URL.
- JavaScript decides which components match the new URL and renders them.
Nothing is thrown away except the components that no longer match. State held in components that stay mounted survives the navigation.
| Aspect | Server-rendered navigation | Client-side navigation |
|---|---|---|
| Who maps URL to content | The server | JavaScript in the browser |
| Request on link click | Full document request | None, or a data request only |
| Page state on navigation | Lost | Kept for components that stay mounted |
| Back button handled by | The browser | Your router, through the History API |
| First load | One HTML response with content | HTML shell, then JavaScript renders content |
The History API
Browsers expose the session history through window.history. Two methods let a script change the URL without loading a page:
history.pushState(state, "", url)adds a new entry to the history stack and changes the address bar.history.replaceState(state, "", url)overwrites the current entry instead of adding one.
Neither method triggers a page load, and neither tells you to re-render. That part is up to your code. The URL must have the same origin as the current page, or the browser throws a SecurityError.
When the user presses the back or forward button, the browser changes the URL itself and fires a popstate event on window. Your code listens for it and renders the matching content. Note that popstate does not fire when you call pushState yourself.
A router in about twenty lines
This example is a complete, minimal router. It has no React, only the History API.
const pages = {
"/": "Home",
"/about": "About",
};
document.body.innerHTML = `
<nav>
<a href="/" data-link>Home</a>
<a href="/about" data-link>About</a>
</nav>
<main id="root"></main>
`;
function render() {
const title = pages[location.pathname] ?? "Not found";
const heading = document.createElement("h1");
heading.textContent = title;
document.querySelector("#root").replaceChildren(heading);
}
document.addEventListener("click", (event) => {
const link = event.target.closest("a[data-link]");
if (!link) return;
event.preventDefault();
history.pushState({}, "", link.getAttribute("href"));
render();
});
window.addEventListener("popstate", render);
render();Each of the three pieces maps to a responsibility of every client-side router:
- The
clickhandler intercepts navigation.preventDefault()stops the browser from requesting a new document, andpushStateupdates the URL. - The
popstatehandler keeps back and forward buttons working. render()turns the currentlocation.pathnameinto UI.
React Router does the same three things. It adds route matching with nested layouts, URL parameters, data loading, form handling, and error boundaries.
Where React fits in
React itself has no concept of URLs. It renders components from state. A router library connects the two:
- It stores the current location (the path, query string, and hash) as state.
- It matches that location against your route definitions.
- It renders the components for the matching routes.
- It updates the location when links are clicked or history changes, which triggers a re-render.
React Router's data router API, which this tutorial uses, adds a step before rendering. It can run a route's loader and action functions, so data fetching and mutations are tied to the URL and not to component effects. Later chapters cover this.
Consequences you need to plan for
Client-side routing changes how the app behaves in a few ways that cause real bugs.
Deep links need server cooperation
A client-side URL like /users/42 exists only in the browser's history. If a user bookmarks it or refreshes the page, the browser sends GET /users/42 to your server. A static file server that has no such file returns a 404. The fix is a fallback rule: for any path that is not a real file, serve index.html, and let the router read the URL from there. Most hosting platforms and dev servers such as Vite do this for you or offer a setting for it. An alternative is the hash router, covered in a later chapter, which avoids the problem by keeping the route after a #.
Browser behavior you must restore
A full page load gives you some behavior for free. A router has to reproduce it:
- Scroll position: the browser resets scroll to the top on a new page. A client-side router must do this itself.
- Focus and announcements: screen readers hear a new page load. After a client-side navigation, nothing is announced unless you manage focus or update the document title.
- Document title:
document.titlestays the same until your code changes it. - Real links: use real
<a href>elements so that middle-click, "open in new tab," and copy-link keep working. Intercept only plain left-clicks without modifier keys. The minimal router above skips this check, but a production router must not.
Initial load is slower to show content
The first request returns a near-empty HTML shell. The user sees content only after the JavaScript bundle downloads and runs. Route-level code splitting, covered in a later chapter, reduces this cost by loading code only for the route being visited.
Common mistakes
- Using a plain
<a href>without intercepting the click. This triggers a full page load and resets all app state. React Router'sLinkcomponent prevents this. - Expecting
popstateto fire afterpushState. It does not. Render explicitly after you push. - Forgetting the server fallback, which makes deep links and refreshes return 404.
- Treating the URL as separate from app state. The path and query string are state that users can copy, bookmark, and share, so put in them what should survive a reload.
Exercise
In the minimal router above, a user clicks the About link, then clicks Home, then presses the back button. Which History API calls and events run for each of the three actions, and what does the user see at the end?
Show answer
Clicking About runs preventDefault, then pushState("/about"), then render, so the page shows About. Clicking Home runs pushState("/") and render, so the page shows Home. Pressing back makes the browser move to the previous history entry, "/about", and fire a popstate event. The popstate handler calls render, which reads location.pathname ("/about"), so the user ends on the About page. No request is sent to the server at any step.
Exercise
A user refreshes the browser on /users/42 in a deployed SPA and sees a 404 from the server, although the link worked when clicked inside the app. Why does this happen, and what is the usual fix?
Show answer
Clicking the link only called pushState, so the server never saw /users/42. A refresh sends a real GET /users/42 request, and the server has no file or route for it. The usual fix is to configure the server or host to return index.html for any path that is not a real static file, so the router can read the URL and render the right route.