In traditional websites, navigating between pages requires the browser to reload the entire HTML page. Modern React applications are built as Single Page Applications (SPAs). They load the page once, and then swap out components dynamically when the URL changes.
To handle page transitions without reloading the page, we use a routing library like React Router or Next.js Routing.
Advertisement
Nextsem Academy
Lesson: p4-7-routing
Slide 1 / 5
P4.7: React Routing
In traditional websites, navigating between pages requires the browser to reload the entire HTML page. Modern React applications are built as Single Page Applications (SPAs). They load the page once, and then swap out components dynamically when the URL changes.
To handle page transitions without reloading the page, we use a routing library like React Router or Next.js Routing.
Slide 2 / 5
1. Traditional vs Client-Side Routing
Traditional Routing: User clicks link -> Browser requests new page -> Server returns HTML -> Full page refresh (slow, white flash).
Client-Side Routing: User clicks link -> React intercept click -> Updates the URL -> Swaps out matching component dynamically (instant, smooth).
Client-Side Routing Speed Increase
Load times (ms) for sub-page transitions.
Slide 3 / 5
2. Using React Router Components
React Router provides three core components to handle client-side routing:
1. BrowserRouter
Wraps your entire application to enable URL tracking.
2. Routes & Route
Defines the mapping between URL paths and React components.
Example
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
Interactive Code
3. Link instead of <a>
Always use the <Link> component for internal navigation. Standard <a href="..."> anchor tags will trigger a full browser page reload, defeating the purpose of an SPA!
Example
import { Link } from 'react-router-dom';
// ❌ WRONG (Triggers full reload)
<a href="/about">About Us</a>
// RIGHT (Client-side routing)
<Link to="/about">About Us</Link>
Interactive Code
Slide 4 / 5
3. Reading Dynamic Parameters
You can capture values from the URL (like user IDs or chapter names) by declaring a wildcard path: