Sub topic 1
How Client-Side Routing Works
Prerequisites
This chapter assumes you know JavaScript modules, React function components, JSX, hooks, and basic URL structure. You should also understand how browser history works.
Client-Side Routing
Client-side routing chooses which React component to display from the browser's URL. A traditional server-rendered navigation requests a new HTML document. A client-side router usually calls history.pushState() to change the URL without requesting a full document. React then renders the matching route.
The browser still owns the address bar and Back button. React Router listens for history changes and matches the current URL against route definitions.
Setting Up the Router
createBrowserRouter creates a router that uses normal browser URLs. RouterProvider makes that router available to the React component tree.
import { createBrowserRouter, RouterProvider } from "react-router-dom";
function Home() {
return <h1>Home</h1>;
}
function About() {
return <h1>About</h1>;
}
const router = createBrowserRouter([
{ path: "/", element: <Home /> },
{ path: "/about", element: <About /> },
]);
export default function App() {
return <RouterProvider router={router} />;
}A route object contains a path pattern and the React element to render. The router checks the current location and selects the best matching route.
Defining Routes and Matching Paths
Paths are URL patterns. /about matches exactly that pathname. A dynamic segment starts with a colon, such as /users/:userId; it matches one path segment and makes its value available through useParams.
More specific route patterns should describe the pages that need different components. A catch-all pattern such as * can handle unknown URLs with a 404 component.
Navigating with Link and NavLink
Use Link for application navigation. It updates the URL without a full page reload.
NavLink has the same navigation behavior but also provides an isActive value. Use it to style the link for the current route.
import { Link, NavLink } from "react-router-dom";
export function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<NavLink
to="/about"
className={({ isActive }) => (isActive ? "active" : undefined)}
>
About
</NavLink>
</nav>
);
}Exercise
Why does clicking a React Router Link usually avoid a full page reload?
Show answer
The router intercepts the click, updates browser history, matches the new URL, and renders the new route in React.