Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 50 ยท Practice and Review

Common Mistakes and Debugging

The routing bugs everyone hits: missing Outlet, relative links that go to the wrong place, hooks outside a Router, stale loader data, redirect loops, and how to inspect routes.

Routing bugs have a particular flavor. Nothing crashes, the page just shows the wrong thing, or nothing, or the same thing after you changed it. The cause is almost always one of a short list: a layout that never renders its children, a link that resolves somewhere you did not expect, a hook called in the wrong place, data that was never refetched, or two redirects that chase each other.

This lesson walks through those bugs one at a time. Each section shows the symptom, the cause and the fix. Where it helps, a live example reproduces the bug. The live examples use a small hand-written router built on location.hash (the real React Router cannot be installed in the editor), so they show the same mistakes, not the library's exact internals; code blocks labelled "React Router (read-only)" use the real API. The last section shows how to look inside a router when you do not know what is wrong. Related reading: Nested Routes and Outlet, Relative Links and Relative Routing and Redirects with Navigate.

Mistake 1: the layout that never renders its children

Symptom: you added nested routes, the URL changes, and the layout's heading and links show up, but the child page never does. No error, no warning.

Cause: a parent route with children only provides the slot. The parent component has to place an <Outlet /> where the child should appear. Without it, React Router matches the child correctly and then has nowhere to draw it.

The demo renders the same route tree twice. The left layout forgot its Outlet; the right one has it. Click "Profile" in either panel: the URL is the same for both, only one of them shows the page.

A layout without an Outlet (fails on purpose)

The fix in real React Router is the same one line:

JSX
// SettingsLayout.jsx - React Router (read-only)
import { Outlet } from 'react-router';

export default function SettingsLayout() {
  return (
    <section>
      <h2>Settings</h2>
      <SettingsMenu />
      <Outlet />
    </section>
  );
}

The same mistake in a milder form is the missing index route: /settings matches the layout, but no child claims the empty rest of the URL, so the Outlet renders nothing. Add <Route index element={<Overview />} />.

Symptom: a link with to=".." or to="edit" works on one page and lands on a strange URL on another, or after you refactor the route tree.

Cause: a to that does not start with / is resolved relative to the route that renders the link, not to the browser's address. A .. therefore climbs one route, not one URL segment. If you merge two nested routes into a single route with a longer path, the number of routes changes, and with it what .. means.

The demo resolves the same four links from the page /users/5 in two route trees that produce the same URLs: one with a users route and a nested :id route, one with a single flat route users/:id. The last column shows the other mode, relative="path", which counts URL segments.

The same link, three different targets

The row for .. is the one to remember: it is /users with two routes and / with one flat route, although the visible URL is identical. The fix depends on what you mean. Use an absolute to="/users" when you always mean that page, relative="path" when you want URL-segment arithmetic, and keep the relative form when you want "up one level of the layout", which is common in reusable components. A related mistake is a nested route with an absolute path: a child path="/new" under path="users" is an error in React Router, because a leading slash means "from the root". Write path="new" instead.

JSX
// React Router (read-only)
<Link to="/users">Absolute: always /users</Link>
<Link to=".." relative="path">Up one URL segment</Link>
<Link to="..">Up one route (the default)</Link>

Mistake 3: hooks outside the Router

Symptom: the app crashes with a message such as useNavigate() may be used only in the context of a <Router> component. Similar messages exist for useLocation, useHref (which Link uses) and friends.

Cause: the hook looks up the router in React context, and the component calling it is not a descendant of a router. Three situations produce this again and again:

  • You call useNavigate() in the same component that renders <BrowserRouter>. The provider is below you, not above you. Move the hook into a child component, or move the router up into main.jsx.
  • A component test renders the component on its own. Wrap it in a MemoryRouter (or use createRoutesStub for data mode).
  • A second React root (a portal target, a widget mounted separately, a modal library that renders in another tree) does not inherit context. Portals created with createPortal do keep context, separate createRoot calls do not.

The demo reproduces the error with a stand-in hook that checks its context the same way and throws a message of the same shape. The error is caught by a small error boundary so you can read it.

A hook used outside its Router (fails on purpose)

The first box fails because nothing above GoToCart provides the context; the second works because Router does. In React Router the broken shape looks like this, which is a very common first-day mistake:

JSX
// App.jsx - React Router (read-only)
import { BrowserRouter, useNavigate } from 'react-router';

export default function App() {
  const navigate = useNavigate(); // Error: this component is NOT inside the router yet
  return (
    <BrowserRouter>
      <button onClick={() => navigate('/cart')}>Cart</button>
    </BrowserRouter>
  );
}

The fix is to render <BrowserRouter> in main.jsx around <App />, or to move the button into a child component. Note that useParams is more forgiving than the others: outside a route it simply returns an empty object, which hides the mistake until you read params.id and get undefined.

Mistake 4: stale data after a change

Symptom: you save something, the server has the new value, but the screen keeps showing the old one until the page is reloaded.

Cause: in data mode, loaders run when you navigate and when the router revalidates. The router revalidates after an action finishes. A plain fetch('/api/...', { method: 'POST' }) inside an event handler is invisible to the router: it does not know that anything changed, so nothing runs again. The same applies to changes made by another tab or another user, which no client router can know about without polling.

The demo uses a stand-in "loader" that runs once. The first button changes the server with a plain call. The second runs the change as an action, which revalidates afterwards. The third is useRevalidator().revalidate(), the escape hatch for changes the router did not make.

Plain fetch versus an action

Click "Like (plain fetch)" twice and the two numbers disagree. Press "Revalidate" and they agree again. In real React Router the rule is simple: make changes through actions (a <Form>, useSubmit or a fetcher), so revalidation is automatic, and call useRevalidator() for outside changes (see Revalidation and Caching). The opposite mistake exists too: a shouldRevalidate function that returns false too eagerly makes data stale on purpose, and then forgets it. If data is stale and you have such a function, read it first.

Mistake 5: redirect loops

Symptom: the page flickers, the tab freezes, the URL bounces between two pages, or (for server redirects) the browser stops with "too many redirects".

Cause: two rules each send the user to a place that the other rule sends them away from. The most common version is a guard (a layout route that redirects signed-out visitors to /login) that accidentally wraps the login page itself: to show /login the guard redirects to /login. The second version is a ping-pong between two guards, such as "signed-in users must not see /login" and "users without a role must not see /dashboard".

The demo follows redirects the way a router does, but stops after six hops so the page does not hang, and prints the chain. The rules are plain functions that return the next URL (or null to stay).

Following redirects to find a loop

The fix is always the same idea: every redirect must lead somewhere that does not redirect again for that user. Put /login outside the guarded layout route, give "signed in but not allowed" its own page, and when you send people to /login, remember where they came from with navigation state so that you can send them back once. See Protected Routes and Auth Redirects. Also use replace on redirects (<Navigate to="/login" replace /> or redirect(...) in a loader) so that a loop does not fill the history with entries and the Back button keeps working.

Smaller mistakes that cost an afternoon

  • Comparing params with numbers. useParams() returns strings, so params.id === 5 is always false. Convert with Number(params.id) and validate (see Dynamic Segments and useParams).
  • A plain <a href> for internal links. It triggers a full page load: state is lost, the JavaScript is downloaded and run again, and loaders have no chance to show a pending state. Use Link and NavLink.
  • Calling navigate() while rendering. Navigating is a side effect. Call it from an event handler or an effect, or render <Navigate>. React Router warns: "You should call navigate() in a React.useEffect(), not when your component is first rendered."
  • A nested <Routes> without a trailing /*. A parent route path="users" that renders its own <Routes> only matches /users exactly. Write path="users/*" so deeper URLs still reach it.
  • NavLink to="/" always active. Add end (Link and NavLink).
  • Deep links return 404 from the host. The server must answer every unknown path with index.html for a client router (How Routing Works Under the Hood).
  • No error boundary. A failing loader then shows the library's default "Unexpected Application Error!" screen. Add an errorElement (Error Boundaries and Error Elements).
  • Keys that do not change on navigation. When a form shows different data for /notes/1/edit and /notes/2/edit, React reuses the same component instance, so uncontrolled inputs keep their old text. Give the form key={note.id}.

Debugging: look inside the router

When you do not know why a URL shows what it shows, stop guessing and print the router's own view of the world. These tools help, in rough order of use:

  1. Print the matches. useMatches() returns one entry per matched route, with its id, pathname, params, loader data and handle. If a route you expected is missing, the URL did not match it; if two routes appear, you have a nesting you did not intend.
  2. Print the location. useLocation() gives pathname, search, hash, state and key. Many "bugs" are a wrong search string or state that was lost on reload.
  3. Read router.state. With createBrowserRouter you hold the router object, so in the browser console (after assigning it to window.router in development) you can read router.state.location, router.state.navigation, router.state.loaderData and router.state.errors, and router.routes for the whole tree.
  4. Watch the Network tab. Loader requests appear when navigation or revalidation happens. Missing requests after a mutation mean the router did not revalidate (mistake 4); duplicate requests usually mean two components fetch the same thing.
  5. Use React DevTools. The component tree shows which route elements are mounted. A layout with no child under it points to a missing Outlet.
  6. Check the history. Back-button problems come from push where replace was needed. navigate(-1) goes back in the browser history, which may leave your site.

A throwaway debug component is worth keeping in your toolbox. The demo shows one for the stand-in router; the idea is identical with the real hooks. Click the links and read the panel.

A route debug panel

Click "Lamp 12": the panel lists three matches (root, shop, product) with the params category and id filled in, and the search string. Click "Unknown URL": the matches list is empty, so the routes area renders nothing (in React Router you would see its default 404 screen unless you added a * route). An empty list is the answer to "why does my page show nothing".

In real React Router the same panel is a few lines:

JSX
// RouteDebug.jsx - React Router (read-only)
import { useLocation, useMatches } from 'react-router';

export function RouteDebug() {
  const location = useLocation();
  const matches = useMatches();
  return (
    <pre>
      {JSON.stringify(
        { pathname: location.pathname, search: location.search, state: location.state, matches },
        null,
        2,
      )}
    </pre>
  );
}

Render it only in development (import.meta.env.DEV in Vite) and remove it before shipping.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A nested route matches and the layout renders, but the child page is blank. What is the most likely cause?

    A parent with children only provides the slot. The Outlet is where the matched child is drawn. Without it, the child matches but has no place on the screen.
  2. 2. A link with to='..' behaves differently after you merge two nested routes into one route with a longer path. Why?

    Relative links are resolved against the route hierarchy, not against URL segments. Use an absolute path or relative='path' when you mean URL arithmetic.
  3. 3. useNavigate() throws that it may be used only in the context of a Router. Which setup causes it?

    The provider is a child of that component, so the hook runs above it and finds no router in context. Move the hook into a child, or render the router higher up.
  4. 4. You save a record with a plain fetch POST in an onClick handler and the page shows old data. What is the cleanest fix?

    The router revalidates after actions. A plain fetch is invisible to it, so nothing reloads. useRevalidator is the fallback for changes that did not come from an action.
  5. 5. What is the common root cause of a redirect loop between /login and a guarded page?

    Every redirect must lead to a location that does not redirect again for that user. Keep /login outside the guard and give 'signed in but not allowed' its own page.

Summary

  • A layout shows nothing of its children unless it renders an <Outlet />, and /parent itself needs an index route.
  • Relative links resolve against the route hierarchy, so .. climbs one route; use absolute paths or relative="path" when you mean URL segments.
  • Router hooks need a router above the calling component. Do not call them in the component that renders the router, and wrap components in a MemoryRouter in tests.
  • Change data through actions so the router revalidates; use useRevalidator for outside changes, and be careful with shouldRevalidate.
  • Redirect loops come from rules that point at each other. Keep the login page outside the guard, give denied users their own page and use replace.
  • To debug, print useMatches() and useLocation(), read router.state, watch the Network tab and look at the React DevTools tree.

Next: React Router Interview Questions