Thuta Learning
React
AdvancedWeb DevelopmentIntermediate

React Router Intro

ReactLesson 1825 min

What you'll walk away with

  • Explain how navigation differs between a multi-page website and a single-page app
  • Understand how history.pushState and the popstate event keep the URL and the UI in sync
  • Explain why switching pages with only a state variable breaks refresh, the Back button and shared links
  • Know React Router v7's package name and what the library handles for you

Explain it simply

Client-side routing in plain language

On a classic website, every link click makes the browser ask the server for a whole new HTML page and redraw the entire screen. A React app usually has a single HTML page, and screens such as Home, About or Dashboard are swapped by JavaScript, component for component. Changing screens like this without a page refresh is called client-side routing.

The important part is that the URL in the address bar changes too. The URL is the address of the screen, so bookmarking it, sending it to a friend and pressing Back must all keep working. In React this job is usually done with the React Router library.

Problem → Why → Solution

The problem: pages switched with state alone

Before learning about routers, the first idea for switching pages is a page state variable. Clicking a button changes it and the right component appears, which looks fine at first. But the URL stays / forever: refreshing on the About page lands on Home, pressing Back leaves the site entirely instead of returning to the previous screen, and there is no link to the About page that you could send to anyone.

StateOnlyPages.jsx
function App() {
  const [page, setPage] = useState('home'); // the URL never changes

  return (
    <>
      <button onClick={() => setPage('home')}>Home</button>
      <button onClick={() => setPage('about')}>About</button>
      {page === 'home' ? <Home /> : <About />}
    </>
  );
}
// Refresh on About -> Home again. Back button -> leaves the site.

Why the URL must be the source of truth

The browser remembers refreshes, Back and Forward, bookmarks and shared links through the URL alone; it knows nothing about the state inside your components. So 'which screen to show' has to live in the URL rather than in state, and the UI must be drawn from the URL. Client-side routing exists to keep that link intact without page reloads.

Core concept: the History API links URL and UI

The browser's History API gives client-side routing its two basic parts. window.history.pushState(state, '', '/about') changes the address bar to /about and adds a new entry to the browser history, without sending a request to the server or reloading the page. When the user presses Back or Forward, the browser changes the URL and fires a popstate event on window.

A router combines these two into a loop. When a link is clicked, it stops the normal navigation with preventDefault, calls pushState and asks React to re-render. When popstate fires, it reads the new URL and asks for a re-render too. On every render the router matches the current pathname against its list of routes and shows the matching component, or a 'not found' screen when nothing matches.

There is one server-side detail as well. Opening /about directly, or refreshing there, is an ordinary HTTP request, so the server looks for an /about file. An SPA has no such file, so the server must answer every path with index.html and let the JavaScript router take over. The Vite dev server does this automatically, but production hosting usually needs an 'SPA fallback' or rewrite rule that you configure yourself.

React Router runs this whole loop for you and adds nested layouts, URL parameters, search parameters and navigation hooks on top. In version 7 the package is called react-router; the older react-router-dom package still exists as a re-export of react-router for people upgrading. v7 can be used in three modes, called declarative, data and framework; this tutorial teaches the declarative mode with <BrowserRouter> and <Routes>.

The URL leads; the UI follows
  1. Click a link: preventDefault
  2. pushState updates the URL
  3. Router matches pathname to a route
  4. The matching component renders
  5. Back fires popstate: match again

Never keep 'which screen is showing' in its own state; always derive it from the URL.

General pattern

jsx
// 1. On a link click: stop the page load, change the URL, re-render
event.preventDefault();
window.history.pushState(null, '', newPath);
setPath(newPath);

// 2. On Back/Forward: read the URL the browser restored
window.addEventListener('popstate', () => setPath(window.location.pathname));

// 3. On every render: pick the screen for the current path
const screen = routes[path] ?? notFoundScreen;

Every router, React Router included, has these three steps inside: intercept navigation, listen to history, and match the path to a screen.

Worked example: a tiny router built by hand

The component below does the basic job of client-side routing without any library. You would not hand-write this in production, because nested routes, parameters, scroll restoration and many other details are still missing. Understanding it, though, makes it clear what React Router's <Link> and <Routes> do behind the scenes in the next lesson.

TinyRouter.jsx
import { useEffect, useState } from 'react';

const routes = {
  '/': <h1>Home</h1>,
  '/about': <h1>About us</h1>,
};

export default function TinyRouter() {
  const [path, setPath] = useState(window.location.pathname);

  useEffect(() => {
    const onPopState = () => setPath(window.location.pathname);
    window.addEventListener('popstate', onPopState); // Back / Forward
    return () => window.removeEventListener('popstate', onPopState);
  }, []);

  function navigate(event, to) {
    event.preventDefault(); // stop the full page load
    window.history.pushState(null, '', to); // update the address bar
    setPath(to); // re-render with the matching page
  }

  return (
    <>
      <nav>
        <a href="/" onClick={(e) => navigate(e, '/')}>Home</a> |{' '}
        <a href="/about" onClick={(e) => navigate(e, '/about')}>About</a>
      </nav>
      {routes[path] ?? <h1>Page not found</h1>}
    </>
  );
}

Code breakdown

  1. Path in state, read from the URLconst [path, setPath] = useState(window.location.pathname);

    Instead of a name such as 'home', the state starts from the browser's pathname, so opening /about directly shows About.

  2. Listen for Back and Forwardwindow.addEventListener('popstate', onPopState); // Back / Forward

    Back and Forward change the URL and fire popstate; the handler syncs the path state with the URL again. The cleanup removes the listener.

  3. Intercept the clickevent.preventDefault(); // stop the full page load

    Keeping a real <a href> means the link looks and behaves like a link, including right-click 'open in new tab'. preventDefault only cancels the browser's full page load.

  4. Change the URL without reloadingwindow.history.pushState(null, '', to); // update the address bar

    This updates the address bar and adds a history entry, which is what lets Back return to the previous screen. setPath(to) then asks React to re-render.

  5. Match the path{routes[path] ?? <h1>Page not found</h1>}

    It looks the path up in the routes object and falls back to a not-found heading. React Router can also match patterns such as /users/:id.

You should see
At / it shows the nav and a 'Home' heading. Clicking About changes the address bar to /about and the heading to 'About us' without a page reload. Back returns to / and 'Home'. Any other path, such as /blog, shows 'Page not found'.

Multi-page sites and SPAs side by side

Client-side routing is not free; each approach has strengths and costs. The table compares what happens in each when a link is clicked.

AspectMulti-page siteSPA + client router
On a link clickServer sends new HTMLJavaScript swaps components
In-memory stateLost on every pageKept across navigation
First loadHTML shows at onceWaits for the JS bundle
Server setupA file or route per pathindex.html for every path

To fix the slower first load and the empty HTML that search engines see, some frameworks render pages on the server first and then continue with client-side routing. React Router's framework mode takes this path too, yet the routing basics, deriving the screen from the URL, stay the same.

In real projects

Routing in real projects

Most React apps such as dashboards, online shops and admin panels use client-side routing, so screens switch quickly and state such as a shopping cart survives navigation. When planning routing at the start of a project, teams usually settle the points below.

  • URL design: plan readable, shareable URLs such as /products/42; URLs are effectively a public API that users bookmark.
  • Hosting: configure a fallback rule on the production server or static host that returns index.html for every path, or every refresh returns a 404.
  • Router mode: declarative mode is enough for a plain SPA; if each route needs data loading, read about the data and framework modes in the React Router docs.
  • Accessibility: updating the page title and moving focus to the new content on each screen change matters for screen reader users.

Common mistakes

Common mistakes when starting with routing

Switching screens with state alone

Switching screens with a page state, as in the problem section, breaks refresh, Back and bookmarks. Users press the browser's Back button constantly, so the app feels broken. Keep the current screen in the URL.

Forgetting the server fallback

Everything works in development, but after deploying, refreshing on /about shows the host's 404 page. It is not a code bug: the server is looking for an /about file. Add a rewrite that sends every path to index.html, following your host's docs.

Importing before installing, or mixing package names

Writing import { Link } from 'react-router' before running npm install makes Vite fail with an error such as 'Failed to resolve import'. With v7, import everything from react-router; mixing react-router-dom in some files and react-router in others can hide two installed versions.

Mini challenge

Mini challenge: write your own Link component

React Router's <Link> intercepts only plain clicks and leaves 'open in new tab' actions such as Ctrl/Cmd-click to the browser. Write such a Link component plus a pathname hook for a tiny router, and build an App with Home, Pricing and Contact pages.

  • usePathname() returns [path, setPath] and listens for popstate
  • Link renders an <a href={to}>
  • If Ctrl, Meta, Shift or Alt is held, or it is not the left button, do nothing and let the browser act
  • On a plain click, preventDefault, pushState and call onNavigate(to); unknown paths show 'Page not found'
LinkRouter.jsx
import { useEffect, useState } from 'react';

function usePathname() {
  // TODO: path state from window.location.pathname
  // TODO: popstate listener (with cleanup) that syncs the state
  // TODO: return [path, setPath]
}

function Link({ to, onNavigate, children }) {
  function handleClick(event) {
    // TODO: leave modified clicks (ctrl/meta/shift/alt) and non-left buttons alone
    // TODO: otherwise preventDefault, pushState, then onNavigate(to)
  }
  return null; // TODO: a real <a> with href and onClick
}

const titles = { '/': 'Home', '/pricing': 'Pricing', '/contact': 'Contact' };

export default function App() {
  // TODO: use the hook, render three Links and an <h1> for the current page
  return null;
}

Expected: A plain click on Pricing changes the URL to /pricing and the heading to Pricing with no reload. Ctrl-click (Cmd-click on a Mac) leaves the current tab alone and the browser opens a new tab. Back returns to the previous page, and a path such as /missing shows 'Page not found'.

Show hint

A MouseEvent has event.ctrlKey, event.metaKey, event.shiftKey, event.altKey and event.button (0 is the left button). Returning early skips preventDefault, so the browser's normal behaviour continues.

Show solution
LinkRouter.jsx
import { useEffect, useState } from 'react';

function usePathname() {
  const [path, setPath] = useState(window.location.pathname);
  useEffect(() => {
    const sync = () => setPath(window.location.pathname);
    window.addEventListener('popstate', sync);
    return () => window.removeEventListener('popstate', sync);
  }, []);
  return [path, setPath];
}

function Link({ to, onNavigate, children }) {
  function handleClick(event) {
    const modified = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
    if (modified || event.button !== 0) return; // new tab/window: browser handles it
    event.preventDefault();
    window.history.pushState(null, '', to);
    onNavigate(to);
  }
  return <a href={to} onClick={handleClick}>{children}</a>;
}

const titles = { '/': 'Home', '/pricing': 'Pricing', '/contact': 'Contact' };

export default function App() {
  const [path, setPath] = usePathname();
  return (
    <>
      <nav>
        <Link to="/" onNavigate={setPath}>Home</Link>{' '}
        <Link to="/pricing" onNavigate={setPath}>Pricing</Link>{' '}
        <Link to="/contact" onNavigate={setPath}>Contact</Link>
      </nav>
      <h1>{titles[path] ?? 'Page not found'}</h1>
    </>
  );
}

Quick quiz 1 / 3

What does calling window.history.pushState(null, '', '/about') do?

Quick quiz 2 / 3

After deploying a React SPA to a static host, refreshing on /about shows the host's 404 page. What is the most likely cause?

Quick quiz 3 / 3

What is the main problem with an app that switches screens using const [page, setPage] = useState('home')?

What to remember

  • Client-side routing ties the URL to the component on screen without page reloads
  • pushState changes the URL, popstate reports Back and Forward, and the router matches the path on every render
  • Keep the current screen in the URL; state alone breaks refresh, Back and bookmarks
  • Production servers need a fallback that returns index.html for every path
  • React Router v7 ships as the react-router package, and this tutorial uses its declarative mode

React Router Documentation — React Router

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

React Router Intro | Thuta Learning