Routing
React Router
Master React Router, covering BrowserRouter declarations, programmatic useNavigate calls, useParams dynamic mapping, and searchParams query processing.
1. Learning Objectives
In this lesson, you will learn how to configure client-side navigation in a Single Page Application (SPA). By the end of this topic, you will be able to:
- Differentiate between client-side routing and traditional server-side navigation.
- Set up route paths using
BrowserRouter,Routes, andRoute. - Use
LinkandNavLinkto navigate between pages without reloading. - Trigger programmatic navigation inside functions using the
useNavigateHook. - Extract dynamic route parameters (
useParams) and query search strings (useSearchParams).
2. Overview
Traditional websites trigger a full page reload from the server whenever you click a link. In contrast, React Single Page Applications use **Client-Side Routing** to update the URL and render matching components dynamically in the browser, without reloading the page. React Router is the standard library used to manage this process.
3. Why This Topic Matters
Client-side routing is key to building fluid, app-like web experiences:
- Instant Page Transitions: Intercepting browser link clicks allows you to swap out layout components instantly, avoiding the blank-screen flashes of server-side reloads.
- Deep Linking: Managing route paths in the URL allows users to bookmark specific pages (like `/products/104`) or share search result links (like `/search?q=react`) directly with others.
4. Real-World Analogy
Think of client-side routing like **walking between departments inside a museum**:
- Server-Side Navigation: Every time you want to see a different exhibit, you must leave the building, stand in line, buy a new ticket, and enter through the front gate again (a full page reload).
- Client-Side Routing: You walk freely between different rooms (components) inside the museum. The address of the room you are in changes (the URL updates), but you stay inside the same building. This provides a faster, more seamless experience.
5. Core Concepts
Below is a comparison of `` navigation and programmatic `useNavigate` calls:
| Feature | Link / NavLink Components | useNavigate Hook |
|---|---|---|
| Usage Style | Declarative (used directly in JSX templates). | Imperative (called inside JavaScript functions). |
| HTML Output | Renders an <a href="..."> anchor tag. |
None; triggers routing programmatically. |
| Best Used For | Standard user navigation (menus, nav bars, footer links). | Action-based redirects (e.g. redirecting to dashboard after login). |
6. Syntax & API Reference
This example shows a basic React Router configuration:
7. Visual Diagram
This diagram displays how click events trigger client-side route updates:
8. Live Example — Full Working Code
Below is a complete, single-file HTML page implementing a multi-page app with Home, Search, and User details pages:
What just happened? Clicking the navigation links swaps out the rendered component in the `` block without reloading the page. The `User` component uses the useParams Hook to read the dynamic user ID (88) from the URL, and uses `useNavigate` to redirect programmatically. The `Search` component uses useSearchParams to read and update query parameters in the URL.
9. Interactive Playground
Try It Yourself Challenges:
- Add a new Route matching path
"*"that renders a custom "404 Not Found" component. - Modify the
NavLinkstyles to add an active class that changes the text color of the active page link.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Using vanilla HTML anchor tags directly | Using standard <a href="..."> tags triggers a full page reload from the server, losing the application's local state and slowing down transitions. |
<a href="/home">Home</a> |
<Link to="/home">Home</Link> (intercepts navigation client-side) |
| Calling useNavigate outside BrowserRouter context | Hooks like useNavigate and useParams read routing context from the BrowserRouter provider. Calling them in components declared above the provider causes errors. |
Declaring useNavigate inside the main App component that renders <BrowserRouter>. |
Declare useNavigate inside child components nested *inside* the <BrowserRouter> tags. |
11. Best Practices
- Use Link for user links: Always use `` or `` instead of standard anchor tags.
- Use NavLink for navigation bars: Use `` instead of `` for navigation menus because it automatically adds an `active` class to the link matching the current route.
- Declare fallback routes: Include a wildcard route (`path="*"`) at the end of your routes to display a custom "404 Not Found" component.
12. Browser Compatibility/Requirements
React Router uses the HTML5 History API, which is supported in all modern browsers.
13. Interview Questions
Q1: Explain the difference between client-side routing and traditional server-side routing.
Answer:
- Server-side routing: Clicking a link requests a new HTML document from the server. The browser does a full page reload, losing all local page state.
- Client-side routing: React Router intercepts link clicks. It updates the URL in the address bar using the HTML5 History API and swaps out layout components dynamically, without reloading the page or losing state.
Q2: How do you extract dynamic path parameters and query parameters using React Router Hooks?
Answer: Use the following Hooks: (1) `useParams` returns an object containing key-value mappings for dynamic path segments (e.g. `userId` from `/user/:userId`), and (2) `useSearchParams` returns a read-write pair containing the search query parameters object and an updater function (e.g. reading `?q=react` using `searchParams.get('q')`).
14. Debugging Exercise
Identify why clicking this button throws an exception in the browser console:
Diagnosis: The useNavigate Hook is called inside the App component, which is declared *above* the BrowserRouter component in the render tree. Since the Hook reads context from the router provider, calling it outside the provider context throws an error.
Fix: Wrap the App component in BrowserRouter at a higher level, or move the Hook call and button into a child component nested inside the provider:
15. Practice Exercises
Exercise 1: Create a product details selector page
Build a component named ProductDetail. Set up a route path matching "/products/:productId". Use useParams to display the correct product details, and add a link to navigate back to the product catalog list.
16. Scenario-Based Challenge
The E-Commerce Filters Search Synced State:
You are designing a product search page with filters for price, category, and availability. Instead of saving these filters in local component state, you must sync them with the URL query parameters so users can share links directly. Describe how you would implement this using useSearchParams.
17. Quick Quiz
Q1: Which component is used to link to different routes without triggering a full page reload?
A) <Anchor>
B) <Link>
C) <Redirect>
Answer: B — <Link> is the React Router component used to trigger client-side page transitions without reloads.
18. Summary & Key Takeaways
- Client-side routing updates the URL and DOM dynamically in the browser, without reloading the page.
- Use
LinkorNavLinkinstead of standard anchor tags to link to different pages. - Use the
useParamsHook to read dynamic path parameters. - Use the
useSearchParamsHook to read and update query string parameters in the URL.
19. Cheat Sheet
| Router API element | Purpose |
|---|---|
<Link to="/path"> |
Creates a client-side navigation link. |
const navigate = useNavigate() |
Returns a function to trigger navigation programmatically. |
const { id } = useParams() |
Extracts dynamic parameters from the URL path. |
const [q, setQ] = useSearchParams() |
Reads and updates query parameters in the URL. |