Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 132 ยท Routing and Apps

Client-Side Routing

Learn how client-side routing works in React by building a tiny hash router with context and hooks: links, params, nested layouts, redirects and 404s.

A traditional website has one HTML page per URL. Click a link and the browser asks the server for a new document, throws away the old page and builds the new one. A React application is usually a single page: the browser loads one HTML file and one bundle of JavaScript, and from then on the app decides what to show. Without extra help, though, every screen would live at the same address. The back button would leave your app, you could not bookmark a product, and sharing a link would always land on the home screen.

Client-side routing fixes this. A router connects the URL to the UI in both directions: when the URL changes, it renders the matching components, and when the user clicks a link, it changes the URL without a full page load. In this lesson you will build a small router yourself, from three browser features and two React hooks. Once you have seen how simple the core idea is, the big routers (covered in React Router and Framework Routers) stop being magic.

What a router does

A router has four jobs:

  1. Read the location (the path, the query string and the hash) and tell React when it changes.
  2. Match the location against a list of routes and extract parameters, such as the 42 in /users/42.
  3. Render the components for the matched route, including nested layouts.
  4. Navigate: provide links and functions that change the location without reloading, keeping the back and forward buttons working.

Everything else (loaders, transitions, scroll restoration, code splitting) builds on these.

History routing and hash routing

The browser gives you two ways to put app state into the URL.

The History API (history.pushState, the popstate event) changes the path of the URL without a reload. You get clean URLs such as /users/42. The cost is that the server must return your index.html for every path, otherwise reloading /users/42 asks the server for a file that does not exist and returns a 404. This is called the "SPA fallback" or "rewrite to index". Read-only sketch:

JavaScript
// History routing (read-only: needs a real page, not our sandboxed preview)
function navigate(path) {
  history.pushState(null, '', path);          // change the URL, no reload
  window.dispatchEvent(new PopStateEvent('popstate')); // pushState fires no event itself
}

window.addEventListener('popstate', () => {
  console.log('Location is now', location.pathname);
});

Hash routing stores the route after a #: https://example.com/app#/users/42. Browsers never send the hash part to the server, so no server configuration is needed, links work even when the app is a static file, and changing the hash fires a hashchange event and adds a history entry. The URLs are less pretty, and the hash can no longer be used for in-page anchors.

Our live editor runs your code in a sandboxed frame with an opaque origin where history.pushState throws, so every example in this lesson uses hash routing. The router you build is identical in structure either way: only the two functions "read location" and "change location" would differ.

Step 1: reading the location with useSyncExternalStore

The URL is state that lives outside React. When something outside React owns the state, useSyncExternalStore is the right hook: you give it a subscribe function and a snapshot function, and it keeps components in sync, even during concurrent rendering.

A hash location hook and plain links

Click the links and watch the heading and paragraph change, then use the browser's back button inside the preview if you can. Four things are worth noticing:

  • A hash link is an ordinary <a href="#/about">. The browser handles the click, updates the URL and fires hashchange. No JavaScript click handler is needed, so links keep working with middle click, "open in new tab" and keyboard activation.
  • getSnapshot returns a string. It must return the same value when nothing changed (strings compare by value), otherwise React would loop. Never return a fresh object from it.
  • The third argument is the server snapshot: on the server there is no window, so '/' is used.
  • The if chain at the bottom does not scale. We need a table.

Step 2: matching routes and reading params

A route is a pattern plus something to render. Patterns use :name for a dynamic segment (/users/:id) and * for "anything else". Matching splits both the pattern and the path at the slashes and compares the segments one by one. The query string (?tab=posts) is not part of the match, so we strip it first.

Route matching with params and a 404

Click "User 42": the console prints Matched /users/:id {"id":"42"} and the page shows the id. "Post" matches a different, longer pattern with two params, and "Broken link" falls through every pattern and hits the catch-all * route, which is how a 404 page works in every router. Notes on the design:

  • Order matters. The first matching route wins, so put specific patterns before general ones and the * route last. Real routers rank routes by specificity so that order stops mattering; our toy does not.
  • Params come out as strings. /users/42 gives "42", not the number 42. Convert explicitly (Number(id)) and handle NaN.
  • Decode them. A slug such as hello%20world arrives encoded, hence decodeURIComponent.
  • Params travel by context. A component deep in the tree can call useParams() without prop drilling. See Context.

Never trust the URL. A param is input from the outside world, just like a form field: validate it, handle "user 99999 does not exist", and never put it into dangerouslySetInnerHTML or a database query without escaping. See JSX in Depth.

Step 3: nested routes and layouts

Most apps have shared chrome: a header, a sidebar or a tab bar that stays while the content below it changes. Nested routes model this directly. A parent route renders the layout, and inside it an Outlet marks the place where the matching child route goes. The URL /settings/profile matches two routes at once: the /settings layout and the profile child.

The recipe: resolve returns a list of matches from the outermost to the innermost. A Level component renders the match at its position and gives the next level to an Outlet through context. Also add NavLink, a link that knows whether it is active and sets aria-current="page", which both styles it and tells screen readers where the user is.

Nested routes with layout and Outlet

Click "Settings", then "Billing". The top navigation and the "Settings" heading stay in place, while only the innermost area changes. The highlighted link follows the URL because each NavLink reads the location itself. In the route table, path: '' is an index route: it matches when nothing more of the URL is left, so / shows "Home" and /settings shows "Choose a settings section." A path like projects/:projectId carries its param down to the page via context.

Why nested routing is worth the machinery:

  • Layouts are not re-created. Moving from /settings/profile to /settings/billing keeps AppLayout and SettingsLayout mounted, with their state, scroll position and focus intact. Only the child at the end changes. See Reconciliation and Keys in Depth.
  • Data and error handling can attach to a route level. Real routers let each level load its data and show its own error screen.
  • URLs mirror the UI structure, which keeps navigation predictable.

Step 4: navigating from code, redirects and search params

Links cover most navigation. Sometimes you must navigate from code: after a form is saved, after a login, or when a route has moved. With hash routing that is an assignment to location.hash; location.replace('#/path') swaps the current history entry instead of adding one, which is what a redirect should do (otherwise the back button bounces the user into the redirecting URL again and again).

Filters, sorting and pagination belong in the query string rather than in component state. Then the page is shareable, bookmarkable and survives a reload. URLSearchParams parses and builds the string for you.

navigate, redirect, search params and titles

Open "Follow the old shop link": the console prints Redirecting to /products and you land on the products page. Because the redirect used replace, pressing Back does not return to /old-shop. Click "Sort by price" and the footer shows location: /products?sort=price while the list reorders. The sort order lives in the URL, so in a normal page you could copy the address, reload, or send it to a friend and see the same view (our editor preview starts fresh on every run, so you cannot try that part here). Other observations:

  • <title> inside a component. React 19 hoists a <title> (and <meta>, <link>) rendered anywhere to <head>, which is the simplest way to give each route its own document title. Screen reader users depend on it. See Accessibility in React.
  • Redirects belong in an effect (or in the router's loader), not in the render body: navigating changes state outside React, which is a side effect. See Effects with useEffect.
  • tabIndex={-1} on the heading is a preparation for focus management. After navigation, move focus to the new page's heading (with heading.focus() in an effect) so keyboard and screen reader users know the page has changed, since an SPA gives no automatic announcement.
  • replace: true for the sort buttons avoids filling the history with one entry per click. Use a normal push when the user would expect Back to undo the change, for example when moving to page 2.

What a full router adds

Our router has about 80 lines and is perfectly usable for a small app. Production routers add the long tail:

Feature Why it matters
Route ranking /users/new beats /users/:id regardless of order
Link behaviour Ignores modified clicks, target="_blank" and download; supports prefetching
Scroll restoration Back returns to the old scroll position; new pages start at the top
Blocking navigation Warn about unsaved changes
Relative links to="../billing" inside nested routes
Data loading Fetch before rendering, with pending and error states per route
Code splitting Download a route's code only when it is visited (see Code Splitting with lazy and Suspense)
Server rendering Render the matched route on the server for SEO and speed (see Server-Side Rendering and Hydration)
Transitions Keep the old page visible while the new one loads (see Transitions, useTransition and useDeferredValue)

In practice you will use React Router, TanStack Router, or the router of a framework like Next.js, and the next lesson tours them. Everything you built here maps directly: useLocation, useParams, Link, NavLink, Outlet, useNavigate, useSearchParams and Navigate are the names you will meet.

Common mistakes

  • Using <a href="/about"> for internal links in a history router. That reloads the whole page. Use the router's Link, which intercepts the click.
  • Using onClick with navigate on a div or button for navigation. You lose middle click, right click "copy link", and accessibility. A link is an <a>.
  • Putting everything in component state instead of the URL. If the user should be able to share or reload it (selected tab, filters, page number, open item id), it belongs in the URL.
  • Redirecting in render. Do it in an effect or loader, and use replace.
  • Forgetting the server fallback with history routing: reloading a deep link returns a 404.
  • Not handling unknown params and 404s. Always render something useful for a user id that does not exist.
  • No focus or title update on navigation, which leaves screen reader users unaware that anything changed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does our live editor use hash routing for its router examples?

    The preview runs in a sandboxed frame, so the History API is unavailable. Hash routing needs only location.hash and the hashchange event, and also needs no server configuration.
  2. 2. Which hook is the right one to subscribe a component to the browser URL, which lives outside React?

    useSyncExternalStore takes a subscribe function and a snapshot function and keeps all components consistent, even with concurrent rendering. The snapshot must return the same value when nothing changed.
  3. 3. What does an index route (path: '') do inside a parent route?

    An index route is the default child. For /settings the layout renders and its Outlet shows the index route, until the user picks /settings/profile or another child.
  4. 4. A user clicks a filter button that changes only how a list is sorted. Which history behavior is usually best?

    Small refinements of the same page usually replace the entry; navigations to another page, or to a new page of results, push one. The state still lives in the query string so the view is shareable.
  5. 5. Why should a redirect run in an effect rather than during render?

    Render may run more than once and must not change anything outside the component. Navigating is an effect on an external system, so it belongs in an effect, an event handler or a router loader.

Summary

  • A client-side router syncs the URL with the UI: it reads the location, matches routes, renders components and navigates without reloading.
  • History routing gives clean paths but needs a server fallback to index.html; hash routing needs no server and works in our sandboxed editor.
  • useSyncExternalStore is the correct way to subscribe React to the URL; links are plain anchors that the router enhances.
  • Matching splits patterns into segments, extracts :params (as strings, to be decoded and validated) and falls back to a * route for 404 pages.
  • Nested routes use layouts with an Outlet, keep parent layouts mounted, and support index routes; NavLink marks the current page with aria-current.
  • Keep shareable state in the query string with URLSearchParams, redirect with replace from effects or loaders, set the document title, and move focus on navigation.

Next: React Router and Framework Routers