DEV Community

DevFrontier
DevFrontier

Posted on

React Router: A Complete Study Guide for Interviews

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

c. Navigation

  • Link: For client-side navigation.
<Link to="/about">Go to About</Link>
Enter fullscreen mode Exit fullscreen mode
  • useNavigate: Hook for programmatic navigation.
const navigate = useNavigate();
navigate("/profile");
Enter fullscreen mode Exit fullscreen mode

d. Dynamic Routing

- Define routes with parameters:

<Route path="/users/:id" element={<UserProfile />} />
Enter fullscreen mode Exit fullscreen mode

- Access params:

import { useParams } from "react-router-dom";
const { id } = useParams();
Enter fullscreen mode Exit fullscreen mode

e. Nested Routes
Example:

<Route path="/dashboard" element={<Dashboard />}>
  <Route path="settings" element={<Settings />} />
  <Route path="profile" element={<Profile />} />
</Route>
Enter fullscreen mode Exit fullscreen mode

Inside Dashboard component:

<Outlet />
Enter fullscreen mode Exit fullscreen mode

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>} />
Enter fullscreen mode Exit fullscreen mode

b. Redirects

  • Use Navigate component.
<Navigate to="/login" replace />
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

d. Search Params

  • Handle query strings:
const [searchParams, setSearchParams] = useSearchParams();
const filter = searchParams.get("filter") || "";

setSearchParams({ filter: "active" });
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

โœ… 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)