Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Interview Essentials
  1. 1.Introduction to React & Basic Setup
  2. 2.JSX, Functional Components & Props
  3. 3.State Management with useState & useEffect
  4. 4.Conditional Rendering & List Management
  5. 5.Event Handling & Form Management
  6. 6.React Router for SPA Navigation
  7. 7.Context API for Global State
  8. 8.Working with Refs & the DOM
  9. 9.Advanced Component Patterns: HOCs & Render Props
  10. 10.Building Reusable Logic with Custom Hooks
  11. 11.Performance Optimization with Memoization
  12. 12.Error Boundaries for Robust UIs
  13. 13.Concurrent React & Suspense
  14. 14.Testing React Components with RTL
  15. 15.Advanced State Management (Overview)
React Interview Essentials
06

React · Lesson 6 of 15 · 4 min

React Router for SPA Navigation

Interviewers use React Router to test your understanding of application structure, URL state management, and user experience in a single-page world.

After this, you'll be able to explain exactly how client-side routing works, why it's necessary, and how to structure a multi-page React application. You'll know the key hooks and components and be ready to answer questions about advanced patterns like protected routes and code splitting.

How to Explain Client-Side Routing

Single Page Applications break the browser's default navigation. In a traditional multi-page app, clicking a link requests a new HTML document from the server. In an SPA, you only load one HTML shell. JavaScript handles the rest.

Client-side routing libraries like React Router fix this. They use the browser's History API (pushState, replaceState) to manipulate the URL without triggering a server request. The library listens for URL changes, matches the path to a configured route, and renders the corresponding React component.

The trap: Don't just define what an SPA is. Interviewers know what it is. Instead, explain the trade-off. You get a faster, app-like user experience, but you take on the responsibility of managing URL state, navigation history, and accessibility on the client.

The Core Routing Toolkit

You only need to know a handful of components and hooks to be effective. Don't memorize the whole API; master these.

  • <BrowserRouter>: The context provider. It wraps your root component and enables routing for the entire app.
  • <Routes> and <Route>: The mapping system. <Routes> is a container that finds the best <Route> match for the current URL. <Route> connects a path to a component element.
  • <Link>: The user-facing navigation element. It renders an <a> tag but intercepts the click to prevent a page reload, letting the router handle it.
  • useParams(): The hook for reading dynamic URL segments, like the id from /products/:id.
  • useNavigate(): The hook for programmatic navigation. Use it to redirect a user after an action, like a form submission or login.
  • <Outlet>: The placeholder for child routes. It's essential for creating nested layouts, like a dashboard with a persistent sidebar.

An interviewer will ask: "What's the difference between a <Link> and an <a> tag?"

Your answer: "A standard <a> tag triggers a full page refresh and a new request to the server. A <Link> component from React Router prevents that default behavior. It updates the URL via the History API and lets the router re-render the appropriate components without a page load, preserving the SPA experience. You use <a> for external links and <Link> for internal navigation."

Building a Realistic Route Structure

A real app needs static pages, dynamic pages based on an ID, nested layouts, and a 404 page. You can define all of this declaratively in one place. This example covers all four patterns.

// src/App.tsx
import React from 'react';
import {
  BrowserRouter,
  Routes,
  Route,
  NavLink,
  Outlet,
  useParams,
  useNavigate,
} from 'react-router-dom';

// Component Stubs
const HomePage = () => <h2>Home</h2>;
const AboutPage = () => <h2>About</h2>;
const UserListPage = () => <h2>Users - <NavLink to="/users/123">View User 123</NavLink></h2>;
const NotFoundPage = () => <h2>404 Not Found</h2>;

const UserDetailPage = () => {
  const { userId } = useParams();
  return <h2>User Details for ID: {userId}</h2>;
};

const DashboardLayout = () => (
  <div>
    <h2>Dashboard</h2>
    <nav>
      <NavLink to="profile">Profile</NavLink> | <NavLink to="settings">Settings</NavLink>
    </nav>
    <hr />
    <Outlet /> {/* Child routes render here */}
  </div>
);

const ProfilePage = () => {
    const navigate = useNavigate();
    return (
        <div>
            <h3>My Profile</h3>
            <button onClick={() => navigate('/')}>Go Home</button>
        </div>
    );
};
const SettingsPage = () => <h3>Account Settings</h3>;


const App: React.FC = () => {
  return (
    <BrowserRouter>
      <nav>
        <NavLink to="/">Home</NavLink> | <NavLink to="/about">About</NavLink> | <NavLink to="/users">Users</NavLink> | <NavLink to="/dashboard">Dashboard</NavLink>
      </nav>

      <main>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/about" element={<AboutPage />} />
          <Route path="/users" element={<UserListPage />} />
          <Route path="/users/:userId" element={<UserDetailPage />} />

          {/* Nested Routes */}
          <Route path="/dashboard" element={<DashboardLayout />}>
            <Route index element={<h3>Dashboard Home</h3>} />
            <Route path="profile" element={<ProfilePage />} />
            <Route path="settings" element={<SettingsPage />} />
          </Route>

          {/* Catch-all 404 Route */}
          <Route path="*" element={<NotFoundPage />} />
        </Routes>
      </main>
    </BrowserRouter>
  );
};

export default App;

Nested routes are powerful for layouts. When the URL is /dashboard/profile, React Router first matches /dashboard and renders DashboardLayout. It then continues matching the rest of the URL against the nested routes and renders ProfilePage where the <Outlet /> is.

Answering Advanced Routing Questions

Senior-level interviews will go beyond the basics. Be prepared to discuss architecture and performance.

How do you implement a protected route?

You create a wrapper component. This component checks for an authentication condition (e.g., a user object in state or a token in storage). If the user is authenticated, it renders the <Outlet /> component, which allows the requested child route to appear. If not, it uses the <Navigate> component to redirect the user to a login page.

const ProtectedRoute = ({ user }) => {
  if (!user) {
    // Redirects to login, preserving the intended destination
    return <Navigate to="/login" replace />;
  }
  return <Outlet />;
};

// In your Routes setup:
<Route element={<ProtectedRoute user={currentUser} />}>
  <Route path="/admin" element={<AdminDashboard />} />
</Route>

How do you improve performance for large apps?

The main strategy is code splitting. By default, all your component code is bundled together. For a large app, this initial bundle can be huge.

You can use React.lazy() to dynamically import components only when their route is rendered for the first time. Wrap your <Routes> with React's <Suspense> component to provide a fallback UI (like a spinner) while the component code is being fetched. This significantly reduces your initial bundle size and improves Time to Interactive.

When would you use HashRouter instead of BrowserRouter?

Almost never. BrowserRouter is the standard. It uses clean URLs (/about) and relies on the server being configured to serve your index.html for any SPA path.

HashRouter uses a hash in the URL (/#/about). It's a fallback for environments where you can't configure the server, like some static file hosts. The part after the # is not sent to the server, so it "just works" without server-side configuration. But the URLs are less clean, and it can have implications for server-side rendering and SEO.

Try it

Refactor the example code to include a protected /admin route. Create a wrapper component ProtectedRoute that checks a hardcoded isLoggedIn flag. If the flag is false, it should redirect to the home page (/). This should take you about 15 minutes.

Next: We'll see how to share state like that isLoggedIn flag across your entire app with the Context API for Global State.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Event Handling & Form Management

Next

Context API for Global State