React Router basics
React Router does client side routing: the URL decides which component is on screen, without a full page reload. This covers BrowserRouter, Routes/Route, nested layouts with Outlet, Link/NavLink, URL params and navigation from code (React Router v7).
43.1 Why is it used?
- Switching pages with useState changes the screen but not the URL.
- Refresh lands back on Home, a Cart link cannot be shared, and the browser back button leaves the whole app.
- With a router the URL is the source of truth, so refresh, sharing and back/forward all work.
React (JSX)
import { useState } from "react";export default function App() { const [page, setPage] = useState("Home"); return ( <> <button onClick={() => setPage("Home")}> Home </button> <button onClick={() => setPage("Cart")}> Cart </button> <h1>{page}</h1> </> );}Output
-- initial --URL: localhost:5173/[button] Home[button] Cart# Home -- after clicking Cart --URL: localhost:5173/[button] Home[button] Cart# Cart43.2 Setup: BrowserRouter
- In v7 everything is imported from the single react-router package.
- Wrap the whole App in <BrowserRouter>; it watches the browser URL and informs components when it changes.
Terminal
npm install react-routerReact (JSX)
import { createRoot } from "react-dom/client";import { BrowserRouter } from "react-router";import App from "./App"; const root = document.getElementById("root");createRoot(root).render( <BrowserRouter> <App /> </BrowserRouter>);43.3 Routes and Route
- <Routes> is the container; each <Route> has a path (matched against the URL) and an element (what renders).
- path="/" shows Home, path="cart" shows Cart.
- path="*" is a catch-all for unknown URLs: show a NotFound / 404 page.
React (JSX)
import { Routes, Route } from "react-router";import Home from "./pages/Home";import Cart from "./pages/Cart";import NotFound from "./pages/NotFound"; export default function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="cart" element={<Cart />} /> <Route path="*" element={<NotFound />} /> </Routes> );}Output
-- / --URL: localhost:5173/# Home -- /cart --URL: localhost:5173/cart[button] Back[button] Place order -- /xyz --URL: localhost:5173/xyz# 404: Page not found43.4 Nested routes and layout
- A parent Route with no path and element={<Layout />} wraps all pages, so the navbar is written once.
- An index route renders on the parent's own URL (/).
- Child paths have no leading slash: they are relative to the parent.
React (JSX)
import { Routes, Route } from "react-router";import Layout from "./Layout";import { Home, Cart, Product } from "./pages";export default function App() { return ( <Routes> <Route element={<Layout />}> <Route index element={<Home />} /> <Route path="cart" element={<Cart />} /> <Route path="products/:id" element={<Product />} /> </Route> </Routes> );}43.5 Outlet and NavLink
- <Outlet /> is the placeholder where the matching child page renders; the nav stays the same.
- <NavLink> is a special <Link>: it changes the URL without reload and adds an active class to the current link by itself.
- No extra state is needed to highlight the active link.
React (JSX)
import { NavLink, Outlet } from "react-router"; export default function Layout() { return ( <> <nav> <NavLink to="/">Home</NavLink> <NavLink to="/cart">Cart</NavLink> </nav> <main> <Outlet /> </main> </> );}Output
-- / --URL: localhost:5173/Nav: Home (active) | Cart# Home -- /cart --URL: localhost:5173/cartNav: Home | Cart (active)[button] Back[button] Place order- Step 1
1.Link / NavLink click or navigate() changes the URL
- Step 2
2.BrowserRouter notices the new URL
- Step 3
3.Routes finds the matching path
- Step 4
4.Parent Layout renders (nav stays)
- Step 5
5.Matching child page renders inside <Outlet />
No page reload, so app state stays safe
43.6 URL params: useParams
- path="products/:id" is a dynamic segment: any value can come in place of :id.
- useParams() reads it from the URL: /products/42 gives { id: "42" }.
React (JSX)
import { useParams } from "react-router"; // Route: path="products/:id"export default function Product() { const { id } = useParams(); return <h1>Product #{id}</h1>;}Output
URL: localhost:5173/products/42Nav: Home | Cart# Product #4243.7 Navigation from code: useNavigate
- useNavigate() returns a navigate function for navigation after an event, e.g. after placing an order.
- navigate("/") goes to Home; navigate(-1) works like the browser back button.
React (JSX)
import { useNavigate } from "react-router"; export default function Cart() { const navigate = useNavigate(); return ( <> <button onClick={() => navigate(-1)}> Back </button> <button onClick={() => navigate("/")}> Place order </button> </> );}Output
-- on /cart --URL: localhost:5173/cartNav: Home | Cart (active)[button] Back[button] Place order -- after Place order --URL: localhost:5173/Nav: Home (active) | Cart# Home43.8 Checkpoint: id + 1
- URL is /products/7 and the heading shows id + 1. Result: 71, not 8.
- URL params are always strings, so + joins them. Convert first: Number(id) + 1.
React (JSX)
import { useParams } from "react-router"; // URL: /products/7export default function Product() { const { id } = useParams(); return <h1>Next: {id + 1}</h1>;}Output
URL: localhost:5173/products/7# Next: 7143.9 API summary
| API | Purpose | Example |
|---|---|---|
| BrowserRouter | Tracks the browser URL | <BrowserRouter><App /></BrowserRouter> |
| Routes / Route | Map a path to an element | <Route path="cart" element={<Cart />} /> |
| index route | Renders on the parent URL | <Route index element={<Home />} /> |
| path="*" | Catch-all 404 | <Route path="*" element={<NotFound />} /> |
| Outlet | Where the child route renders | <Outlet /> inside Layout |
| Link / NavLink | Navigate without reload (NavLink adds active class) | <NavLink to="/cart">Cart</NavLink> |
| useParams | Read :id from the URL (string) | const { id } = useParams() |
| useNavigate | Navigate from code | navigate("/"), navigate(-1) |
43.10 Common mistakes
- Using <a href> inside the app: full page reload, all React state resets and the app feels slow. Use <Link to>.
- Doing math on params without Number().
- Myth: every route is a separate HTML page from the server. The server sends one index.html and JavaScript routes in the browser.
- So on deploy the server must return index.html for every URL, or a refresh on /cart gives 404.
React (JSX)
export function Nav() { return ( <nav> <a href="/">Home</a> <a href="/cart">Cart</a> </nav> );}React (JSX)
import { Link } from "react-router"; export function Nav() { return ( <nav> <Link to="/">Home</Link> <Link to="/cart">Cart</Link> </nav> );}43.11 Best practices
- In v7 import from react-router; react-router-dom is only kept for compatibility.
- Shared UI like the navbar: a layout route plus Outlet.
- Keep a * catch-all route in every app.
- Link/NavLink for in-app navigation, useNavigate for navigation from code.
43.12 Interview tips
- React Router is a client side routing library: it renders components based on the URL without a full page reload.
- BrowserRouter tracks the URL; Routes and Route map a path to a component; a parent's Outlet renders the nested child.
- Dynamic segments come from useParams and are always strings.
- useNavigate handles navigation from code (navigate(-1) = back).
- Mention the server fallback to index.html for SPA deploys.