React Router – Complete Beginner Guide

1. What is Routing in React?

Routing allows your React application to switch between different UI pages without reloading the browser. Instead of loading new HTML files, React simply changes components based on the URL.

2. BrowserRouter, Routes, Route

BrowserRouter

It wraps your entire app and tells React Router to enable routing. Think of it as: “Enable URL-based navigation”.

import { BrowserRouter } from "react-router-dom";

<BrowserRouter>
   <App />
</BrowserRouter>
    

Routes

A container that holds all your Route components.

Route

Used to define which component should load on which URL.

<Routes>
  <Route path="/about" element={<About />} />
</Routes>
    

3. What are path and element?

They are props (like HTML attributes) of the <Route /> component.

path

Defines which URL should load the component.

element

Defines which component should appear.

<Route path="/contact" element={<Contact />} />
    

4. Why React Router uses element instead of component?

Old versions used:

<Route component={Home} />
    

But this caused unnecessary re-renders and made it difficult to pass props. Now React Router expects:

<Route element={<Home />} />
    

This gives:

5. Dynamic Routing (URL Parameters)

Dynamic routing means the URL can contain variables.

<Route path="/user/:id" element={<UserProfile />} />
    

Retrieve the id using useParams:

import { useParams } from "react-router-dom";

const UserProfile = () => {
  const { id } = useParams();
  return <h1>User ID: {id}</h1>;
};
    

6. Nested Routes (Pages inside pages)

This is used for dashboards, layouts, or sections.

<Routes>
  <Route path="/dashboard" element={<Dashboard />}>
      <Route path="profile" element={<Profile />} />
      <Route path="settings" element={<Settings />} />
  </Route>
</Routes>
    

Inside Dashboard:

import { Outlet } from "react-router-dom";

const Dashboard = () => (
  <div>
    <Sidebar />
    <Outlet />  {/* Nested pages appear here */}
  </div>
);
    

7. Private Routing (Protected Routes)

Used for Login-based pages.

Step 1: Create PrivateRoute

import { Navigate } from "react-router-dom";

const PrivateRoute = ({ element }) => {
  const isLoggedIn = localStorage.getItem("token");

  return isLoggedIn ? element : <Navigate to="/login" />;
};
    

Step 2: Use it in routes

<Route
  path="/dashboard"
  element={<PrivateRoute element={<Dashboard />} />}
/>
    

8. Lazy Loading & Code Splitting (Bonus)

import { lazy, Suspense } from "react";

const About = lazy(() => import("./About"));

<Suspense fallback={<h1>Loading...</h1>}>
  <Route path="/about" element={<About />} />
</Suspense>
    

React only loads the component when needed → improves performance.

9. HashRouter vs BrowserRouter

10. Summary