🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Router: Nested Routes, Params, and Guards

React NavigationRoutingđŸŸĸ Free Lesson

What You'll Learn

  • 1Predict which element React Router renders for a given URL
  • 2Structure nested routes with layout routes and a single outlet
  • 3Read dynamic params, search parameters, and programmatic navigation correctly
  • 4Place authentication checks where they protect data as well as markup

The URL is state you do not own

A browser address is shared state. It appears in bookmarks, in history, in the link someone pastes into chat, and in the referrer header of the next site your visitor opens. Frameworks that keep a copy of the route in a useState, or that hide navigation inside a boolean such as showSettings, lose all of that the moment the user refreshes, presses back, or opens a tab in a new window.

Client-side routing exists to keep the page alive while the address still tells the truth. The router listens to history changes, matches the pathname against your route table, and renders the matching element into the outlet. Everything else in a routing library, including nested layouts, scroll restoration, prefetching, and guards, is built on top of that one guarantee: the visible screen corresponds to the current URL.

How matching chooses exactly one route

Routes are ranked rather than simply tested in order. A static segment beats a dynamic one, and a dynamic segment beats a splat, so /settings/profile wins over /settings/:page for that address even if both are declared. This ranking means adding a specific route never requires you to reorder the tree, and it also means a wildcard route placed too high can shadow everything beneath it.

<BrowserRouter>
  <Routes>
    <Route path="/" element={<SiteLayout />}>
      <Route index element={<Home />} />
      <Route path="posts" element={<PostsLayout />}>
        <Route index element={<PostList />} />
        <Route path=":slug" element={<PostView />} />
      </Route>
      <Route path="settings/*" element={<Settings />} />
      <Route path="*" element={<NotFound />} />
    </Route>
  </Routes>
</BrowserRouter>

Here the parent route at / provides the chrome, the index child fills the outlet when the path is exactly /, and the splat at the bottom catches anything unmatched. Reading the tree top to bottom is reading the address left to right.

Layout routes and the shared outlet

A route without an element but with children is a pathless layout: it wraps its children without contributing a segment. That is how you keep an authenticated shell, a tab bar, or a breadcrumb trail mounted while the content beneath it swaps. The parent renders an outlet, and the matched child fills it.

The payoff is persistence. Because the layout never unmounts, a sidebar keeps its scroll position, a video player keeps playing, and expensive providers keep their data while you navigate between sibling pages. The cost is that anything the layout owns resets only when you leave the branch, which is exactly what you want for a shell and exactly what you do not want for per-page state.

Reading params, search strings, and navigation

Dynamic segments arrive through a hook, query strings do not, and confusing the two is a frequent source of bugs. Params are part of the route definition; search parameters are free-form user input that must be parsed and validated.

import { useParams, useSearchParams, useNavigate, Link } from 'react-router-dom';

function ArticlePage() {
  const { slug } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

  const page = Math.max(1, Number(searchParams.get('page')) || 1);
  const theme = searchParams.get('theme') || 'light';

  const changePage = (next) => {
    const params = new URLSearchParams(searchParams);
    params.set('page', String(next));
    setSearchParams(params, { replace: true });
  };

  return (
    <article>
      <h1>{slug}</h1>
      <p>Page {page}, theme {theme}</p>
      <button type="button" onClick={() => changePage(page + 1)}>Next</button>
      <button type="button" onClick={() => navigate(-1)}>Go back</button>
      <Link to={`/posts/${slug}?page=${page + 1}`}>Next page</Link>
    </article>
  );
}

Two details worth memorising. First, setSearchParams preserves the rest of the query because you rebuilt it from the current object rather than starting fresh. Second, use replace on updates that should not stack history entries, such as a filter change, while pushes are reserved for navigation the user expects to reverse with the back button.

Where protection actually belongs

A guard can live in several places, and they are not equivalent. Rendering a different element when the user is unauthenticated protects the markup only; the data request behind it still fires for anyone who guesses the address.

Guard locationProtectsWeakness
Conditional element in the route tableMarkup, roughlyData loaders may still run, and the check repeats on every render
Wrapper component around a protected branchMarkup and local effectsEasy to forget on new branches; still client-side
Loader or data function on the routeData and markupThe check must be duplicated for each protected loader
Server middleware or edge functionData, markup, and APIRequires the session to be readable outside React
Database row-level rulesThe data itselfThe strongest guarantee, and the only one that survives a modified client

Production applications layer at least two of these. The route guard gives the visitor a clean redirect, the server middleware refuses the request, and the data layer enforces ownership so a leaked identifier is useless.

Loading data before the page paints

Route-level loaders remove the flash of empty content that comes from mounting a component and fetching inside it. The loader runs during navigation, its result is handed to the element as props, and React Router can suspend the transition until the data is ready. The component then renders once with real content instead of three times through loading, error, and success.

Prefer this shape for anything a page needs immediately, and keep client-side fetching for interactions: search-as-you-type, infinite scroll, and data that refreshes while the page is already visible. Mixing the two without a rule produces two competing sources of truth for the same value.

Scroll, focus, and the back button

A routed application inherits a browser behaviour that single-page demos never exercise: the scroll position. By default, navigating to a new route keeps the previous position, so a user who clicks an article from the bottom of a list lands halfway down the next page. React Router can restore per-path scroll positions on back and forward, and reset on fresh navigation, but the reset is your job to declare rather than something the library can infer.

Focus is equally important and rarely handled. After a client-side navigation, focus stays on the link that was clicked, so a screen reader user hears nothing about the new page. The pattern that works is to focus the main heading of the new route, or a container element marked with tabIndex equal to minus one, in a small effect that runs on location change. Announce the page title as well if the route updates the document title asynchronously.

The back button deserves a final note. Because history entries are user-facing state, treat every push as a promise that back returns somewhere sensible. Filter panels that push a history entry per keystroke make back useless, while pushes on meaningful transitions such as opening a detail page make it essential. Choosing replace over push is one of the highest-leverage usability decisions in a router, and it costs nothing to get right at the time of writing the navigation call.

Common Mistakes

Guarding only the component and assuming the loader or fetch behind it is safe

Fix: Check the session in the data layer and on the server, then redirect for a friendly experience

Building navigation state with useState instead of the address bar

Fix: Keep filters, tabs, and pagination in the query string so refresh and back behave

Parsing a query parameter and using it without validating it

Fix: Coerce types, clamp ranges, and fall back to defaults before the value reaches render

Reordering routes to make a static path match before a dynamic one

Fix: Let the router rank routes and instead place splats at the deepest level they should catch

Best Practices

  • Use pathless layout routes to share a shell without adding a URL segment
  • Prefer Link and navigate over window.location so the history stack stays intact
  • Set replace on filter and sort updates so back returns to the previous page, not the previous filter
  • Keep the splat route last in its branch so it only catches true misses
  • Render a not-found element rather than an empty outlet so users are never stranded

Key Takeaways

  • Routes are ranked by specificity, so static segments beat dynamic ones and splats rank last
  • Layout routes mount once and fill an outlet, which preserves expensive state across navigation
  • Params come from the route; search parameters come from the user and need parsing and validation
  • Client-side guards improve experience but only server-side checks protect data
  • Loaders fetch during navigation, avoiding the loading-to-success render churn of in-component fetches
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement