Client-Side Routing

Map URLs to screens with React Router or TanStack Router: nested layouts, params, navigation and protected routes.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Hooks, Refs and State Patterns

A single-page application (SPA) loads one HTML page and swaps screens in JavaScript. A router keeps the URL in sync with what is on screen so that links, the back button, bookmarks and sharing all work as users expect.

Core ideas

  • Route definitions map paths to components: /, /products, /products/:id.
  • Nested routes and layouts: a shared shell (navbar, sidebar) renders an <Outlet /> where child routes appear.
  • Dynamic params (:id) and search params (?page=2&sort=price). Put shareable UI state such as filters, tabs and pagination in the URL, not only in component state.
  • Navigation: <Link> for normal navigation (it renders a real anchor, so it is accessible), navigate() after actions like login.
  • Loaders and actions (React Router data APIs, TanStack Router) fetch data before a route renders, avoiding waterfalls.
  • Not found and error routes, plus protected routes that redirect unauthenticated users.
  • Code splitting per route with lazy loading.

Choosing a router

React Router is the long-standing default and doubles as a framework (the successor to Remix). TanStack Router offers fully type-safe routes and search params. Meta-frameworks like Next.js use file-based routing instead, where folders define routes.

Pitfalls

Using <div onClick> instead of links; losing scroll position or focus on navigation (move focus to the new page heading for screen reader users); forgetting to configure the host to serve index.html for all paths, which makes refreshes 404.

Good enough to move on

You can build an app with a shared layout, a list page whose filters live in search params, a detail page using a route param, a protected settings area and a 404 page.

Key concepts

  • Route definitions and nested layouts
  • Route params and search params
  • Link and programmatic navigation
  • Protected routes and redirects
  • Loaders and data routers
  • Route-based code splitting
  • React Router
  • TanStack Router: Type-safe routes and search params
  • Focus and scroll management

Mini project

Add routing to your product catalogue: layout with navbar, /products with filters and page number stored in search params, /products/:id detail, a login-protected /account area and a custom 404.

Check yourself

Why should a product list's active filters live in the URL rather than only in useState?

Free resources