π What Is Routing?
Routing is the mechanism that decides what content to show based on the URL.
Example:
/β Home Page/aboutβ About Page/profileβ Profile Page
In traditional websites, each URL loads a new HTML page.
In React, routing usually happens without reloading the page.
π SPA vs MPA
π§© MPA (Multi Page Application)
Each page is a separate HTML file
Full page reload on every navigation
Slower user experience
Server handles routing
Example: Traditional PHP, JSP, or older websites
β‘ SPA (Single Page Application)
Only one HTML file
Page content changes dynamically
No full page reload
Faster and smoother UX
Routing handled on the client side
React applications are SPAs!!
β Why Routing Is Needed in React
Without routing:
React apps would be stuck on one screen
Youβd have to manually manage views using conditions
With routing:
Clean URLs (
/login,/dashboard)Better navigation
Browser back/forward buttons work
Easy to scale large applications
π§ Client-Side Routing Concept
In React:
The browser URL changes
React decides which component to render
No request is sent to the server for a new page
π JavaScript intercepts navigation and updates the UI.
π Key Concepts
π URL
Represents the current route
Example:
https://example.com/products/1
π Browser History
Maintains navigation stack
Enables:
Back button
Forward button
Programmatic navigation
π Page Refresh vs Route Change
Action | What Happens |
|---|---|
Page Refresh | App reloads, state resets |
Route Change | Component updates, state preserved |
π¦ What Is react-router-dom?
react-router-dom is the official routing library for React web apps.
It provides:
Routing components
Navigation helpers
Hooks for routing logic
π Router Types Overview
π BrowserRouter
Uses HTML5 History API
Clean URLs (
/about)Most commonly used
Recommended for modern apps
π HashRouter
Uses hash (
#/about)Works without server configuration
Used in static hosting environments
π Recommended Folder Structure
src/
ββ pages/
β ββ Home.jsx
β ββ About.jsx
β ββ Contact.jsx
ββ App.jsx
ββ main.jsxπ Each page = one route
π οΈ Hands-On: Setup React Router
1οΈβ£ Install React Router
npm install react-router-dom@62οΈβ£ Wrap App with BrowserRouter
main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<BrowserRouter>
<App />
</BrowserRouter>
);π Code Explanation
BrowserRouter is the traffic controller that tells React which page to show for which URL.
What itβs doing here π§
<BrowserRouter>
<App />
</BrowserRouter>It listens to the browser URL (
/,/about,/profile)It keeps UI in sync with the URL
It lets React Router features work:
<Routes>/<Route><Link>/<NavLink>useNavigate,useParams
Without it β
β‘οΈ React has no idea the URL changed.
π Weβll focus on React Router v6 because:
Itβs stable
Widely used in production
Easier for learning fundamentals