← Back to React, page 2

react-0035 · Medium mid

How does client-side routing work with React Router? Explain routes, nested layouts, params and loaders.

React Router matches the browser URL against a list of routes and renders the matching components without a full page reload. Nested routes render children through Outlet inside a layout. Dynamic segments like :id are read with useParams, and in data mode a route's loader fetches data before rendering, available through useLoaderData. Link and NavLink change the URL without a request to the server.

Full answer

In a single-page app the server returns one HTML page, and JavaScript decides what to show for each URL. A router listens for URL changes, finds the matching route and renders its component. Links update the address with the History API, so there is no page reload.

A route has a path and a component. Paths can contain dynamic segments: students/:id matches /students/2, and useParams() returns { id: '2' }. A splat path * catches unknown URLs and is the usual place for a Not Found page.

Nested routes mirror nested UI. A parent route renders a layout, such as a navigation bar, and an <Outlet /> marks where the matching child appears. An index route is the default child for the parent's own path.

React Router has three modes: declarative (BrowserRouter with Routes and Route elements), data (createBrowserRouter with route objects, loaders, actions and RouterProvider), and framework (a Vite plugin that adds file-based features and server rendering). Data mode, used in the example, lets a route declare a loader. The router calls it before rendering, so the component gets data with useLoaderData() and avoids the render-then-fetch waterfall. Actions handle form submissions and then revalidate the loaders.

Navigation uses Link for a plain link and NavLink, which adds an active class for styling the current page. For code-driven navigation, use useNavigate, and for redirects in loaders, return redirect('/login'). Alternatives are TanStack Router, which has type-safe routes, and the file routing of Next.js. Choose by the framework you are already using.

Remember the server too. For a deployed SPA, every URL must serve index.html, otherwise a refresh on /students returns a 404 from the host.

jsx
import {
  createBrowserRouter,
  Link,
  NavLink,
  Outlet,
  RouterProvider,
  useLoaderData,
  useParams,
} from 'react-router';

const students = [
  { id: '1', name: 'Asha' },
  { id: '2', name: 'Ravi' },
];

function Layout() {
  return (
    <div>
      <nav>
        <NavLink to="/">Home</NavLink> <NavLink to="/students">Students</NavLink>
      </nav>
      <Outlet />
    </div>
  );
}

function Home() {
  return <h1>Home</h1>;
}

function StudentList() {
  const list = useLoaderData();
  return (
    <ul>
      {list.map((s) => (
        <li key={s.id}>
          <Link to={'/students/' + s.id}>{s.name}</Link>
        </li>
      ))}
    </ul>
  );
}

function StudentDetail() {
  const { id } = useParams();
  const student = useLoaderData();
  return (
    <h2>
      Student {id}: {student.name}
    </h2>
  );
}

function NotFound() {
  return <h2>Page not found</h2>;
}

const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    children: [
      { index: true, Component: Home },
      { path: 'students', loader: () => students, Component: StudentList },
      {
        path: 'students/:id',
        loader: ({ params }) => students.find((s) => s.id === params.id),
        Component: StudentDetail,
      },
      { path: '*', Component: NotFound },
    ],
  },
]);

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

The Layout stays on screen while the Outlet swaps the page. The loaders return their data before the page components render. The check clicked Students and then the Ravi link. Run output, one snapshot per page: home page: Home StudentsHome students page: Home StudentsAshaRavi detail page: Home StudentsStudent 2: Ravi

Key points

  • A router maps URLs to components and updates the address without reloading the page.
  • Nested routes use Outlet. Dynamic segments such as :id are read with useParams.
  • Data mode adds loaders and actions, which fetch before render and avoid waterfalls.
  • Link and NavLink navigate without a server request. useNavigate is for code-driven moves.
  • A static host must send index.html for all paths so refresh works.

Common mistakes

  • Using a plain anchor tag, which reloads the page, instead of Link.
  • Forgetting an index route or a catch-all route.
  • Forgetting that the host must serve index.html for deep links.
  • Fetching in a component effect when a loader would remove the waterfall.
  • Mixing up the modes and importing APIs that exist only in framework mode.

Follow-ups

  • How do loaders and actions avoid fetch waterfalls?
  • How would you protect a route that needs a logged-in user?
  • How does route-level code splitting work with a router?

Tips

  • Name the three router modes. It shows current knowledge of the library.
  • Explain Outlet with a layout example.
  • Mention the server fallback to index.html. It is a classic deployment bug.