React Routing Interview Guide
Introduction
Section titled “Introduction”Routing is the process of navigating between different pages/components in a Single Page Application (SPA) without reloading the browser. React applications commonly use React Router for client-side routing.
<Route path="/home" element={<Home />} />React Router
Section titled “React Router”React Router enables navigation between views in React applications.
Features
Section titled “Features”- Client-side routing
- Dynamic routing
- Nested routing
- Route parameters
- Lazy loading support
Installation
Section titled “Installation”npm install react-router-domBrowserRouter
Section titled “BrowserRouter”BrowserRouter enables routing using the HTML5 History API.
import { BrowserRouter } from "react-router-dom";
<BrowserRouter> <App /></BrowserRouter>It updates the URL without refreshing the page.
BrowserRouter vs HashRouter
Section titled “BrowserRouter vs HashRouter”| BrowserRouter | HashRouter |
|---|---|
| Uses History API | Uses URL hash (#) |
| Clean URLs | URLs contain # |
| Requires server configuration | No server configuration |
| Preferred for production | Useful for static hosting |
BrowserRouter:https://site.com/home
HashRouter:https://site.com/#/homeBasic Routing Components
Section titled “Basic Routing Components”Defines which component should render for a path.
<Route path="/about" element={<About />} />Routes
Section titled “Routes”Routes replaces Switch in React Router v6.
<Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /></Routes>Navigates without refreshing the page.
<Link to="/about">About</Link>Avoid:
<a href="/about">About</a>NavLink
Section titled “NavLink”Supports active styling.
<NavLink to="/home">Home</NavLink><NavLink to="/home" className={({ isActive }) => (isActive ? "active" : "")}/>Navigation Hooks
Section titled “Navigation Hooks”useNavigate
Section titled “useNavigate”const navigate = useNavigate();
navigate("/dashboard");const handleLogin = () => { navigate("/home");};Passing State
Section titled “Passing State”navigate("/profile", { state: { name: "John" }});Retrieve it:
const location = useLocation();
console.log(location.state.name);useLocation
Section titled “useLocation”const location = useLocation();
console.log(location.pathname);Useful for:
- Active menus
- Analytics
- Breadcrumbs
useParams
Section titled “useParams”Route:
<Route path="/user/:id" element={<User />} />URL:
/user/101Component:
const { id } = useParams();
console.log(id);Output:
101Dynamic Routes
Section titled “Dynamic Routes”/user/:id/product/:productId/order/:orderIdExample:
<Route path="/product/:id" element={<Product />} />Nested Routes
Section titled “Nested Routes”<Route path="/dashboard" element={<Dashboard />}> <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /></Route>Dashboard:
<Outlet />Outlet
Section titled “Outlet”function Dashboard() { return ( <> <Sidebar /> <Outlet /> </> );}Protected Routes
Section titled “Protected Routes”const ProtectedRoute = ({ children }) => { const isAuthenticated = true;
return isAuthenticated ? children : <Navigate to="/login" />;};Usage:
<Route path="/dashboard" element={ <ProtectedRoute> <Dashboard /> </ProtectedRoute> }/>See the JWT Authentication in React Interview Guide for wiring this pattern up against real token checks.
Navigate Component
Section titled “Navigate Component”<Navigate to="/login" />Equivalent:
navigate("/login");404 Handling
Section titled “404 Handling”<Route path="*" element={<NotFound />} />Lazy Loading Routes
Section titled “Lazy Loading Routes”Wrap a route’s element in React.lazy/Suspense so its bundle downloads only when the user navigates to it. See the React Code Splitting Interview Guide for the full route-based splitting pattern and internal chunk-loading flow.
Query Parameters
Section titled “Query Parameters”URL:
/products?page=1&sort=ascconst [searchParams] = useSearchParams();
const page = searchParams.get("page");const sort = searchParams.get("sort");Route Parameters vs Query Parameters
Section titled “Route Parameters vs Query Parameters”| Route Parameters | Query Parameters |
|---|---|
/user/101 |
/products?page=2 |
| Identify a specific resource | Filtering, sorting, pagination |
// Route/user/:idRole-Based Routing
Section titled “Role-Based Routing”if (user.role !== "ADMIN") { return <Navigate to="/unauthorized" />;}Routing Performance Optimization
Section titled “Routing Performance Optimization”- Route-based code splitting
- Lazy loading
- Memoization
- Avoid unnecessary re-renders
- Prefetch critical routes
const UserPage = lazy(() => import("./UserPage"));How React Router Works
Section titled “How React Router Works”flowchart LR
A[User changes URL] --> B[History API updates location]
B --> C[React Router detects change]
C --> D[Matches best route]
D --> E[Renders corresponding component]
E --> F[No full page refresh]
Steps:
- Browser URL changes.
- History API updates the URL.
- React Router listens for changes.
- Matching route is found.
- Correct component is rendered.
- Navigation occurs without a page refresh.
Client-side vs Server-side Routing
Section titled “Client-side vs Server-side Routing”| Client-side | Server-side |
|---|---|
| React Router | Traditional MVC |
| No page refresh | Full page refresh |
| Faster navigation | Slower |
| SPA | MPA |
Enterprise Routing Design
Section titled “Enterprise Routing Design”Recommended structure:
routes/- authRoutes.js- adminRoutes.js- customerRoutes.js- appRoutes.jsBest practices:
- Feature-based route organization
- Lazy-load modules
- Role-based access control
- Route guards
- Error boundaries
- 404 handling
- Centralized route constants
Key Takeaways
Section titled “Key Takeaways”- React Router enables efficient client-side navigation in SPAs.
- Prefer
BrowserRouterfor production unless static hosting requiresHashRouter. - Use hooks like
useNavigate,useLocation,useParams, anduseSearchParamsfor routing logic. - Nested routes with
Outletimprove layout composition. - Protected routes, lazy loading, and route-based code splitting improve security and performance.
- Organize routes by feature/module for scalable enterprise applications.