Tech Interview RoomStudy guides

React Ecosystem

How does routing work with React Router (and data loaders)?

Intermediate · 2 min read · Lesson 5 of 7 in React Ecosystem

React Router (v7, now one package react-router) maps URLs to components. It can be used in three ways: declarative (<BrowserRouter> + <Routes>), data mode (createBrowserRouter with loaders and actions), or framework mode (the former Remix: file routes, SSR, type-safe loaders).

Core features

  • Nested routes with <Outlet /> for layouts; index routes; * for not found.
  • Dynamic segments /orders/:id read with useParams(); query strings with useSearchParams() (great for filters and pagination, shareable URLs).
  • <Link> / <NavLink> (active styles) and useNavigate().
  • Loaders fetch data before rendering the route (no render-then-fetch waterfall); actions handle form submissions; useNavigation() shows pending state; errorElement / ErrorBoundary per route.
  • Lazy routes (lazy: () => import(...)) for code splitting.
  • Protected routes: redirect in a loader (throw redirect('/login')) or wrap with an auth layout.

TanStack Router is an alternative with fully type-safe routes and search params.

Example

tsx
import { createBrowserRouter, RouterProvider, Outlet, NavLink, useLoaderData, redirect, useSearchParams } from 'react-router';

async function requireUser() {
  const res = await fetch('/api/me');
  if (res.status === 401) throw redirect('/login');
  return res.json();
}

const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />,
    errorElement: <p>Something went wrong.</p>,
    children: [
      { index: true, lazy: () => import('./routes/home') },
      {
        path: 'orders',
        loader: async ({ request }) => {
          await requireUser();
          const status = new URL(request.url).searchParams.get('status') ?? 'ALL';
          return fetch(`/api/orders?status=${status}`).then(r => r.json());
        },
        element: <Orders />,
      },
      { path: 'orders/:id', lazy: () => import('./routes/order-detail') },
    ],
  },
]);

function Layout() {
  return (
    <>
      <nav><NavLink to="/">Home</NavLink> <NavLink to="/orders">Orders</NavLink></nav>
      <Outlet />
    </>
  );
}

function Orders() {
  const orders = useLoaderData() as { id: string; total: number }[];
  const [params, setParams] = useSearchParams();
  return (
    <>
      <select value={params.get('status') ?? 'ALL'} onChange={e => setParams({ status: e.target.value })}>
        <option>ALL</option><option>NEW</option><option>PAID</option>
      </select>
      {orders.map(o => <p key={o.id}>{o.id} · ₹{o.total}</p>)}
    </>
  );
}

export default function App() { return <RouterProvider router={router} />; }

Follow-up questions interviewers ask

Try answering each one before you open it.

Why keep filters in the URL instead of component state?

URL state survives refreshes, can be bookmarked and shared, works with the back button, and lets loaders fetch the right data before rendering. Component state is lost on reload and invisible to other parts of the app.