React Router

Client-side routing for Single Page Applications

Routes Link NavLink useParams

Table of Contents

1. Introduction: What is React Router?

React Router is the standard routing library for React applications. It enables client-side routing, allowing you to navigate between different components without refreshing the page.

Analogy: React Router acts like a traffic controller for your app. When a user clicks a link or types a URL, it directs them to the correct "page" (component) while keeping the app running smoothly as a Single Page Application (SPA).

JSX// Without React Router: Multi-page app (full page reload) <a href="/about">About</a> // With React Router: Single Page App (no reload!) <Link to="/about">About</Link>
  • Declarative routing (routes as components)
  • Nested routes for complex layouts
  • Dynamic routing with URL parameters
  • Programmatic navigation with hooks
  • Lazy loading for code splitting

2. Why React Router? (Single Page Application Navigation)

In a traditional multi-page website, clicking a link makes the browser request a new HTML file from the server — causing a full page reload that is slow and loses application state.

React Router's solution: Intercept link clicks, update the URL, and render the appropriate component without refreshing the page.

  1. The app loads once (a single HTML page)
  2. React Router listens to URL changes
  3. When URL changes, it matches the path to defined routes
  4. It renders the corresponding component
  5. The page never reloads

3. Installation and Setup

3.1 Installing React Router DOM

Bashnpm install react-router-dom # or: yarn add react-router-dom # or: pnpm add react-router-dom

3.2 Basic Setup with BrowserRouter

JSXimport { BrowserRouter } from 'react-router-dom'; import App from './App'; createRoot(document.getElementById('root')).render( <BrowserRouter> <App /> </BrowserRouter> );

React Router needs to know the current URL and provide routing context to all components.

3.3 Modern Setup with RouterProvider (Data Router API)

JSX// Object-based routes (React Router v6.4+) import { createBrowserRouter, RouterProvider } from 'react-router-dom'; const router = createBrowserRouter([ { path: '/', element: <App />, children: [ { index: true, element: <Home /> }, { path: 'about', element: <About /> }, { path: 'contact', element: <Contact /> }, { path: 'products/:id', element: <ProductDetail /> }, { path: '*', element: <NotFound /> } ] } ]); createRoot(document.getElementById('root')).render( <RouterProvider router={router} /> );
AspectBrowserRouter + RoutesRouterProvider (Data Router)
SyntaxJSX <Routes><Route>createBrowserRouter object/JSX
Data LoadingManual useEffectBuilt-in loaders
Error HandlingManualBuilt-in error boundaries
Best ForSimple apps, beginnersComplex apps, production

4. Routes and Route Components

4.1 Routes Component (Replaces Switch)

JSXimport { Routes, Route } from 'react-router-dom'; function App() { return ( <Routes> <Route path="/products/:id" element={<ProductDetail />} /> <Route path="/products" element={<Products />} /> <Route path="*" element={<NotFound />} /> </Routes> ); }

Important: Routes renders the best matching route. Put more specific paths before catch-all routes.

4.2 Route Component – path and element

PropPurposeExample
pathURL pattern to match/about, /users/:id
elementComponent to render<About />

4.3 Index Routes (Default Sub-routes)

JSXconst router = createBrowserRouter([ { path: '/dashboard', element: <DashboardLayout />, children: [ { index: true, element: <DashboardOverview /> }, { path: 'settings', element: <Settings /> } ] } ]); function DashboardLayout() { return ( <div> <Sidebar /> <Outlet /> {/* Renders index or child route */} </div> ); }

4.4 404 Not Found Route (Catch-all with *)

JSX<Route path="*" element={<NotFound />} /> function NotFound() { return ( <div style={{ textAlign: 'center', padding: '50px' }}> <h1>404 - Page Not Found</h1> <p>The page you're looking for doesn't exist.</p> <Link to="/">Go Back Home</Link> </div> ); }

7. Dynamic Routing with useParams

7.1 Defining Dynamic Routes (Route Parameters)

JSX<Route path="/products/:id" element={<ProductDetail />} /> <Route path="/users/:userId/posts/:postId" element={<PostDetail />} />
Route PatternMatchesParameter Values
/products/:id/products/123{ id: "123" }
/users/:userId/posts/:postId/users/5/posts/42{ userId: "5", postId: "42" }

7.2 Accessing URL Parameters with useParams

JSXimport { useParams } from 'react-router-dom'; function ProductDetail() { const { id } = useParams(); const [product, setProduct] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(`/api/products/${id}`) .then(res => res.json()) .then(data => { setProduct(data); setLoading(false); }); }, [id]); if (loading) return <div>Loading...</div>; return ( <div> <h1>{product.name}</h1> <p>Price: ${product.price}</p> </div> ); }

7.3 Multiple Parameters and Optional Parameters

JSXfunction ProductDetail() { const { categoryId, productId } = useParams(); return <div>Category: {categoryId}, Product: {productId}</div>; } // Optional parameters <Route path="/search/:query?/:page?" element={<SearchResults />} /> function SearchResults() { const { query, page } = useParams(); const currentPage = page || 1; return <div>Searching for: {query || 'all'} (Page {currentPage})</div>; } // All URL params are strings — convert when needed const productId = Number(id);

8. Complete Working Examples

8.1 Example 1: Complete Blog Application

JSXconst router = createBrowserRouter([ { path: '/', element: <BlogLayout />, children: [ { index: true, element: <PostList /> }, { path: 'posts/:slug', element: <PostDetail /> }, { path: 'about', element: <About /> }, { path: '*', element: <NotFound /> } ] } ]); function BlogLayout() { return ( <div> <nav> <NavLink end to="/">Home</NavLink> <NavLink to="/about">About</NavLink> </nav> <Outlet /> </div> ); } function PostDetail() { const { slug } = useParams(); const post = usePost(slug); if (!post) return <p>Post not found</p>; return <article><h1>{post.title}</h1><p>{post.body}</p></article>; }

8.2 Example 2: E-commerce Product Pages

JSXfunction AppRoutes() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/products" element={<ProductList />} /> <Route path="/products/:productId" element={<ProductDetail />} /> <Route path="/cart" element={<Cart />} /> <Route path="*" element={<NotFound />} /> </Routes> ); } function ProductList() { const products = useProducts(); return ( <ul> {products.map(p => ( <li key={p.id}> <Link to={`/products/${p.id}`}>{p.name}</Link> </li> ))} </ul> ); }

8.3 Example 3: User Dashboard with Nested Routes

JSXconst router = createBrowserRouter([ { path: '/dashboard', element: <DashboardLayout />, children: [ { index: true, element: <Overview /> }, { path: 'orders', element: <Orders /> }, { path: 'orders/:orderId', element: <OrderDetail /> }, { path: 'settings', element: <Settings /> } ] } ]); function DashboardLayout() { return ( <div className="dashboard"> <aside> <NavLink end to="/dashboard">Overview</NavLink> <NavLink to="/dashboard/orders">Orders</NavLink> <NavLink to="/dashboard/settings">Settings</NavLink> </aside> <main><Outlet /></main> </div> ); }

9. Common Mistakes and Best Practices

MistakeProblemSolution
No BrowserRouterHooks return undefinedWrap app with router
Using <a> instead of LinkFull page reloadUse Link or NavLink
No 404 routeBlank page on bad URLsAdd path="*"
Missing end on home NavLinkHome stays active everywhereUse end prop
URL params as numbersType mismatchesUse Number() or parseInt()
JSX// DO <Route path="*" element={<NotFound />} /> <NavLink end to="/">Home</NavLink> const productId = Number(id); // DON'T <a href="/about">About</a> // full reload return <h1>{product.name}</h1>; // crash if product undefined

10. Summary Cheat Sheet

JSX// INSTALLATION npm install react-router-dom // BASIC SETUP <BrowserRouter><App /></BrowserRouter> // or <RouterProvider router={router} /> // ROUTES <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/products/:id" element={<ProductDetail />} /> <Route path="*" element={<NotFound />} /> </Routes> // NESTED ROUTES <Route path="/dashboard" element={<Layout />}> <Route index element={<Overview />} /> <Route path="settings" element={<Settings />} /> </Route> // Layout uses <Outlet /> // NAVIGATION <Link to="/about">About</Link> <NavLink end to="/" style={({ isActive }) => ({ fontWeight: isActive ? 'bold' : 'normal' })}>Home</NavLink> // DYNAMIC PARAMS const { id } = useParams(); const productId = Number(id); // PROGRAMMATIC NAVIGATION const navigate = useNavigate(); navigate('/products'); navigate(-1); // go back navigate('edit'); // relative // QUICK REFERENCE // BrowserRouter → Wrap app for routing context // Routes / Route → Define URL → component mapping // Link → Navigate without reload // NavLink → Link with active state // useParams → Read URL parameters // useNavigate → Programmatic navigation // Outlet → Render nested child routes // path="*" → 404 catch-all

Next Steps

  • API Calls – Fetch data for dynamic routes
  • Protected Routes – Auth guards with Context
  • Lazy Loading – React.lazy with routes
  • Redux Toolkit – Global state with routing

React Router MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic React Router MCQs

1

React Router enables:

AClient-side routing in SPAs
BSQL migrations
CCSS preprocessing
DNode clustering
Explanation: Map URLs to components without full reload.
2

BrowserRouter uses:

AHTML5 history API
BHash only always
CWebSockets
DCookies only
Explanation: Clean URLs without # fragment.
3

Route element prop in v6 maps:

Apath to element component
Bonly CSS
Cnpm scripts
Dstate only
Explanation: <Route path="/" element={<Home />} />.
4

Link component vs <a>:

ALink prevents full page reload
BNo difference
CLink reloads page
DLink only external
Explanation: Client-side navigation updates URL and view.
5

useNavigate hook returns:

AFunction to programmatically navigate
BCurrent CSS
CRedux store
DDOM ref
Explanation: navigate('/dashboard') after login.
6

URL parameters read with:

AuseParams
BuseState only
CuseEffect only
DuseRef only
Explanation: const { id } = useParams() for /users/:id.
7

Nested routes render via:

AOutlet in parent layout
BMultiple index.html
Ciframe only
Dalert
Explanation: Parent layout wraps child routes with Outlet.
8

Navigate component is used to:

ARedirect declaratively
BFetch data
CStyle pages
DInstall packages
Explanation: <Navigate to="/login" replace />.
9

Routes must be inside:

ARouter provider (BrowserRouter)
Bbody only raw
Cpackage.json
DCSS file
Explanation: Router supplies routing context.
10

Active link styling uses:

ANavLink with className or style function
Bonly href
ConLoad
DuseMemo only
Explanation: NavLink knows active state from current URL.

10 Advanced React Router MCQs

1

Loader pattern in React Router 6.4+ data APIs:

AFetch before render on route
BReplaces useEffect always
CServer only
DCSS only
Explanation: Loaders centralize data fetching per route.
2

index route in nested config:

ADefault child when parent path matches
B404 page only
CExternal link
DAPI route
Explanation: <Route index element={<Dashboard />} />.
3

useSearchParams manages:

AQuery string state
BPath params only
CCookies only
DRedux
Explanation: ?tab=settings in URL.
4

Protected route pattern:

ACheck auth; render Navigate to login if unauthorized
BAlways public
CDisable Router
DUse only hash router
Explanation: Wrapper component guards children.
5

Lazy route splitting uses:

AReact.lazy + Suspense with route element
Bsync require in Router
CNo components
DjQuery
Explanation: Code-split per page.
6

404 catch-all route path:

Apath="*" element={<NotFound />}
Bpath="404only"
Cno path needed
Dpath="/"
Explanation: Asterisk matches unmatched paths.
7

relative links in nested routes use:

Arelative path or relative Route structure
Babsolute only
Cfull page reload
Dwindow.location only
Explanation: Nested relative navigation simplifies config.
8

History stack replace:true means:

AReplace current entry instead of push
BDelete all history
COpen new tab
DDisable back button forever
Explanation: Avoid duplicate history entries on redirect.
9

Router v6 relative useRoutes helps:

ADefine route objects in JS data structure
BRemove components
CCSS modules
Dnpm
Explanation: Programmatic route config arrays.
10

SSR with Router needs:

AStaticRouter on server, BrowserRouter on client
BOnly HashRouter
CNo hydration
DCRA only
Explanation: Match server and client URL handling.

15 React Router Interview Questions & Answers

Easy Medium Hard
1What is React Router?easy
Answer: Library for declarative routing in React SPAs using URL to render components.
2BrowserRouter vs HashRouter?medium
Answer: BrowserRouter uses clean URLs; HashRouter uses # for legacy servers without fallback.
3How to navigate programmatically in v6?easy
Answer: useNavigate() hook from react-router-dom.
4What is useParams?easy
Answer: Hook returning dynamic URL segment values like :id.
5Purpose of Outlet?medium
Answer: Renders child route inside parent layout for nested routing.
6How to protect routes?medium
Answer: Check authentication; conditionally render Navigate to login or child routes.
7Difference Link vs anchor?easy
Answer: Link intercepts navigation for SPA; anchor causes full document reload.
8What are search params?medium
Answer: Query string key-value pairs after ? in URL.
9Code splitting with router?hard
Answer: Lazy-load route components wrapped in Suspense.
10404 handling?medium
Answer: Define catch-all route with path * rendering NotFound page.
11NavLink benefit?easy
Answer: Applies active styles when route matches current location.
12React Router data APIs (6.4+)?hard
Answer: Loaders and actions co-locate data/mutations with routes.
13Deploy SPA routing on static host?hard
Answer: Configure server fallback to index.html for unknown paths.
14Nested layout pattern?medium
Answer: Parent route with layout component + Outlet for child pages.
15useLocation provides?medium
Answer: Current location object (pathname, search, hash, state).