React Router is the standard routing library for React applications. It enables navigation among views, allows dynamic rendering, and provides client-side routing without refreshing the browser.
1. 🔹 Why Do We Need React Router?
By default, React is a single-page application (SPA) framework. Without routing, navigating between pages would require full page reloads.
React Router solves this by:
- Handling client-side navigation (no reload).
- Synchronizing UI with the browser URL.
- Supporting nested routes and dynamic parameters.
- Allowing protected routes for authentication.
2. 🔹 Core Concepts
a. Router Components
- BrowserRouter: Uses the HTML5 History API. Preferred for modern apps.
- HashRouter: Uses # in the URL (e.g., /#/home). Good for static file servers.
- MemoryRouter: Keeps history in memory (useful for testing).
b. Routes
- Route maps a path to a component.
- Example:
import { BrowserRouter, Routes, Route } from "react-router-dom"; import Home from "./Home"; import About from "./About"; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); }
c. Navigation
- Link: For client-side navigation.
<Link to="/about">Go to About</Link>
- useNavigate: Hook for programmatic navigation.
const navigate = useNavigate(); navigate("/profile");
d. Dynamic Routing
- Define routes with parameters:
<Route path="/users/:id" element={<UserProfile />} />
- Access params:
import { useParams } from "react-router-dom"; const { id } = useParams();
e. Nested Routes
Example:
<Route path="/dashboard" element={<Dashboard />}> <Route path="settings" element={<Settings />} /> <Route path="profile" element={<Profile />} /> </Route>
Inside Dashboard component:
<Outlet />
3. 🔹 Advanced Features
a. Protected Routes
- Restrict access to authenticated users.
const PrivateRoute = ({ children }) => { const isAuth = localStorage.getItem("auth"); return isAuth ? children : <Navigate to="/login" />; }; <Route path="/dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>} />
b. Redirects
- Use Navigate component.
<Navigate to="/login" replace />
c. Lazy Loading with React Router
- Combine React.lazy + Suspense.
const About = React.lazy(() => import("./About")); <Suspense fallback={<div>Loading...</div>}> <Routes> <Route path="/about" element={<About />} /> </Routes> </Suspense>
d. Search Params
- Handle query strings:
const [searchParams, setSearchParams] = useSearchParams(); const filter = searchParams.get("filter") || ""; setSearchParams({ filter: "active" });
4. 🔹 Common Interview Questions
What’s the difference between BrowserRouter and HashRouter?
- BrowserRouter uses clean URLs with the History API.
- HashRouter uses # in URLs for legacy support.
How do you handle protected routes in React Router?
- Create a wrapper component that checks authentication before rendering.
What’s the purpose of useParams, useNavigate, and useLocation?
- useParams: Access route parameters.
- useNavigate: Navigate programmatically.
- useLocation: Get the current URL and state.
How do nested routes work in React Router v6?
- Parent route renders an for child routes.
How do you implement redirection in React Router v6?
- Use component.
5. 🔹 Best Practices
- Always wrap routes in (v6).
- Use lazy loading for performance.
- Keep route configuration centralized if app grows large.
- Combine layout components with nested routes for DRY code.
- Use useLocation when handling redirects after login/logout.
✅ Summary:
React Router is essential for building SPA navigation in React. Understanding routing basics, nested routes, dynamic params, and protected routes will prepare you well for interviews.
🧑💻 React Router Interview Practice Exercises
Exercise 1: Basic Routing
Task:
- Create a simple app with two pages: Home and About.
- Display "Welcome to Home Page" on /.
- Display "About Us" on /about.
- Add navigation links to switch between them.
Solution:
import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; function Home() { return <h2>Welcome to Home Page</h2>; } function About() { return <h2>About Us</h2>; } export default function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> | <Link to="/about">About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); }
Exercise 2: Dynamic Routes
Task:
Build a User page that shows user IDs from the URL.
- /users/1 → "User Profile: 1"
- /users/42 → "User Profile: 42"
Solution:
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom"; function User() { const { id } = useParams(); return <h2>User Profile: {id}</h2>; } export default function App() { return ( <BrowserRouter> <Routes> <Route path="/users/:id" element={<User />} /> </Routes> </BrowserRouter> ); }
Exercise 3: Nested Routes
Task:
- Create a Dashboard with nested routes:
- /dashboard → "Dashboard Home"
- /dashboard/settings → "Dashboard Settings"
Solution:
import { BrowserRouter, Routes, Route, Outlet, Link } from "react-router-dom"; function Dashboard() { return ( <div> <h2>Dashboard</h2> <nav> <Link to="">Home</Link> | <Link to="settings">Settings</Link> </nav> <Outlet /> </div> ); } function DashboardHome() { return <p>Dashboard Home</p>; } function DashboardSettings() { return <p>Dashboard Settings</p>; } export default function App() { return ( <BrowserRouter> <Routes> <Route path="/dashboard" element={<Dashboard />}> <Route index element={<DashboardHome />} /> <Route path="settings" element={<DashboardSettings />} /> </Route> </Routes> </BrowserRouter> ); }
Exercise 4: Protected Route
Task:
Create a protected Profile page.
- If logged in → Show "Welcome to your profile".
- If not logged in → Redirect to /login.
Solution:
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"; function Login() { return <h2>Please log in</h2>; } function Profile() { return <h2>Welcome to your profile</h2>; } function PrivateRoute({ children }) { const isAuthenticated = false; // change to true for testing return isAuthenticated ? children : <Navigate to="/login" />; } export default function App() { return ( <BrowserRouter> <Routes> <Route path="/login" element={<Login />} /> <Route path="/profile" element={<PrivateRoute><Profile /></PrivateRoute>} /> </Routes> </BrowserRouter> ); }
Exercise 5: Search Params
Task:
Create a Products page that filters items by query string.
- /products?category=shoes → show "Showing shoes".
- /products?category=shirts → show "Showing shirts".
Solution:
import { BrowserRouter, Routes, Route, useSearchParams } from "react-router-dom"; function Products() { const [searchParams] = useSearchParams(); const category = searchParams.get("category") || "all"; return <h2>Showing {category}</h2>; } export default function App() { return ( <BrowserRouter> <Routes> <Route path="/products" element={<Products />} /> </Routes> </BrowserRouter> ); }
Exercise 6: Redirect After Login
Task:
When user logs in, redirect them back to the page they tried to visit.
Solution:
import { BrowserRouter, Routes, Route, Navigate, useLocation, useNavigate } from "react-router-dom"; function Login() { const navigate = useNavigate(); const location = useLocation(); const from = location.state?.from?.pathname || "/"; const handleLogin = () => { localStorage.setItem("auth", "true"); navigate(from, { replace: true }); }; return <button onClick={handleLogin}>Login</button>; } function Profile() { return <h2>Profile Page</h2>; } function PrivateRoute({ children }) { const isAuth = localStorage.getItem("auth"); const location = useLocation(); return isAuth ? children : <Navigate to="/login" state={{ from: location }} />; } export default function App() { return ( <BrowserRouter> <Routes> <Route path="/login" element={<Login />} /> <Route path="/profile" element={<PrivateRoute><Profile /></PrivateRoute>} /> </Routes> </BrowserRouter> ); }
✅ Summary of What You Practiced
- Basic routing with Routes & Route
- Dynamic route params with useParams
- Nested routes with Outlet
- Protected routes & redirection
- Working with query strings
- Preserving navigation state after login
Top comments (0)