React · Lesson 10 of 15 · 3 min
Client-Side Routing with React Router
This is about explaining the "why" of SPAs and demonstrating you can structure a complex app, not just listing API names.
After this, you'll be able to explain the core trade-off of client-side routing and build common UI patterns like nested layouts and dynamic pages. This is a standard interview topic used to gauge your understanding of application architecture.
The Client vs. Server Trade-off
In a traditional multi-page app, the server maps a URL to an HTML document. Clicking a link means a full page request and reload. This is server-side routing.
Client-side routing, used in Single Page Applications (SPAs), intercepts navigation. JavaScript updates the browser's URL using the History API (pushState, replaceState) and then re-renders the React component tree to show the new "page". No full-page reload occurs.
The interview question: "Compare client-side and server-side routing."
Start with the user experience: client-side feels faster after the initial load because you only fetch data, not entire HTML pages. Then, state the trade-off: the initial load is heavier because you download a larger JavaScript bundle containing the app's framework, logic, and templates. This impacts metrics like Time to Interactive (TTI). A good answer shows you think about performance beyond just the obvious "no page reloads."
How React Router Manages Navigation
React Router intercepts link clicks and maps the URL to your component hierarchy. It's a declarative way to manage what the user sees.
The flow is straightforward:
- A user clicks a
<Link>component. - React Router prevents the browser's default navigation.
- It updates the URL in the address bar using the History API.
- It matches the new URL against its defined
<Route>components. - The matching component is rendered, updating the UI.
The trap: Using a standard <a href="..."> tag for internal navigation. This bypasses the router and triggers a full page reload, destroying any client-side state and defeating the purpose of an SPA. Use <a> tags only for links to external sites.
Structuring Routes for Common Patterns
Most applications aren't just a flat list of pages. You need layouts, dynamic content pages, and catch-all 404s. React Router handles this with nested routes, path parameters, and the <Outlet /> component.
- Path Parameters (
:id): Define dynamic segments in a route's path. TheuseParamshook gives you access to the actual value from the URL (e.g.,/products/123gives youproductId: '123'). - Nested Routes: Define routes inside other routes to create parent-child relationships. This is perfect for shared layouts, like a dashboard with a persistent sidebar.
- Outlet: A component you place in a parent route's element. It acts as a placeholder, rendering the matched child route's element.
This single component demonstrates a complete, realistic structure.
import {
BrowserRouter,
Routes,
Route,
Link,
NavLink,
useParams,
Outlet,
useNavigate,
} from 'react-router-dom';
// A layout component for a shared dashboard structure
const DashboardLayout = () => (
<div style={{ display: 'flex' }}>
<nav style={{ borderRight: '1px solid #ccc', padding: '1rem' }}>
<h3>Dashboard</h3>
<NavLink to="/dashboard/profile">Profile</NavLink><br />
<NavLink to="/dashboard/settings">Settings</NavLink>
</nav>
<main style={{ padding: '1rem' }}>
{/* Child routes will render here */}
<Outlet />
</main>
</div>
);
// A component that uses a path parameter
const ProductDetail = () => {
const { productId } = useParams<{ productId: string }>();
const navigate = useNavigate();
return (
<div>
<h2>Details for Product {productId}</h2>
<button onClick={() => navigate('/products')}>Back to Products</button>
</div>
);
};
// Your main App component defines the routing structure
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/products">Products</Link> | <Link to="/dashboard">Dashboard</Link>
</nav>
<hr />
<Routes>
<Route path="/" element={<h2>Home</h2>} />
<Route path="/products" element={<h2>Products List</h2>} />
<Route path="/products/:productId" element={<ProductDetail />} />
{/* Nested routes: DashboardLayout is the parent */}
<Route path="/dashboard" element={<DashboardLayout />}>
<Route path="profile" element={<h3>Profile Page</h3>} />
<Route path="settings" element={<h3>Settings Page</h3>} />
</Route>
{/* Catch-all 404 route */}
<Route path="*" element={<h2>404 Not Found</h2>} />
</Routes>
</BrowserRouter>
);
}
export default App;
When to Navigate Programmatically
Sometimes you need to change routes based on logic, not a user click. This is called programmatic navigation. The useNavigate hook provides a function to do this.
The primary use cases are:
- After an action: Redirecting a user after a successful form submission (e.g.,
navigate('/dashboard')after login). - Protecting routes: If a user tries to access an authenticated route like
/accountwithout being logged in, you can check their auth state in a component or custom hook and callnavigate('/login', { replace: true }). Thereplaceoption prevents the user from hitting the "back" button and returning to the protected page.
Don't overuse it. For standard navigation, a declarative <Link> is clearer and more accessible.
Try it
Modify the code example to create a "protected" route. Create a fake isLoggedIn boolean. If a user tries to access /dashboard and isLoggedIn is false, they should be immediately redirected to the home page (/). Use useNavigate to accomplish this.
Next: Forms, Validation & Data Fetching Patterns
Lock it in — apply this lesson under interview conditions.