Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 50 ยท Practice and Review

React Router Interview Questions

25 React Router interview questions with concise answers: routing modes, nested routes, params, loaders, actions, fetchers, errors, auth and testing, plus runnable stand-in demos.

A React Router interview rarely asks you to recite the API. It checks whether you understand how a URL becomes a screen: how a path is matched, how nested routes compose layouts, where data is loaded, and what happens after a form is submitted. The 25 questions below cover the ones that come up most often, with short answers you could say out loud in under a minute.

How to use this page:

  • Answer first, read second. Say the answer in your own words, then compare. The bold phrases are the points interviewers listen for.
  • Follow the links. Each answer points to the lesson that explains the idea in depth.
  • Know the version. The answers target React Router v7. When something changed from v5 or v6, we say so.

The live demos use a small hand-written stand-in built from React and plain JavaScript, because the sandbox cannot install react-router. Code that uses the real library is shown in read-only blocks. Each demo says which parts are real and which are imitations.

Fundamentals

1. What problem does React Router solve?

A single-page app has one HTML document, but users expect many addresses: they bookmark, share and refresh them, and use the back button. React Router maps the URL to a tree of components and keeps the two in sync without a full page reload. Without it you would track "which page am I on" in state and lose deep links and history. See What Is React Router?.

2. What are the three modes of React Router v7?

Declarative mode (<BrowserRouter>, <Routes>, <Route>) gives matching, links and navigation. Data mode (createBrowserRouter plus <RouterProvider>) adds loader, action, pending state and error elements to route objects. Framework mode (the Vite plugin and a routes.ts file) adds server rendering, type generation, code splitting and deployment tooling on top of data mode. Each mode builds on the previous one, so you can upgrade step by step. See Choosing Between Declarative, Data and Framework Mode.

3. How does it relate to Remix, and what changed in v7?

Remix and React Router shared the same core team and code. Remix v2 features were folded into React Router v7: framework mode is what Remix v2 was, and the Remix package no longer receives new features. In v7 the main package is react-router; react-router-dom still exists but only re-exports it. See Migrating From v5, v6 and Remix.

4. How does client-side routing work underneath?

The router calls history.pushState (or replaceState) to change the address without loading a page, listens for the popstate event for back and forward, and re-renders based on the new location. Because every URL must still work when typed directly, the server must return index.html for unknown paths (or the app must use hash routing). See How Routing Works Under the Hood.

5. What is the difference between BrowserRouter and HashRouter?

BrowserRouter produces clean paths (/about) with the History API and needs server support for deep links. HashRouter keeps the route after a # (/#/about), which the server never sees, so it works on any static host but looks worse and gives search engines less to index. In data mode the equivalents are createBrowserRouter and createHashRouter.

Matching and navigation

6. How does React Router choose between several matching routes?

It ranks all matches by specificity, not by the order you wrote them. Static segments beat dynamic ones (/users/new beats /users/:id), longer paths beat shorter ones, and a splat (*) loses to everything else. The demo uses a simplified scoring rule to show the idea; the real algorithm is more detailed, but the outcome for these cases is the same.

Specific routes beat general ones

With /users/new the winner is new user form (score 20), ahead of user detail (13), users splat (8) and catch-all (-2). With /users/42 the winner is user detail with {"id":"42"}, and with /users/42/edit it is users splat with {"*":"42/edit"}. See Routes and Matching.

7. What is an index route?

A child route with index instead of a path. It renders in the parent's <Outlet> when the URL matches the parent exactly, so /dashboard can show an overview while /dashboard/settings shows another child. Without an index route the outlet is simply empty at the parent URL.

A plain <a href> makes the browser load a new document and throws away your app state. Link renders an anchor but intercepts the click, updates the history and re-renders. NavLink is a Link that knows whether it is active or pending, so it can add a class, a style or aria-current="page". Use end on a link to / (or any parent path) or it counts as active for every child URL. See Link and NavLink.

9. How do you handle a 404 page?

Add a route with path="*" (a splat) that renders a not-found component. Ranking guarantees it only wins when nothing else matches. In a pure client app the HTTP status is still 200 for the HTML shell; to send a real 404 you need server rendering (framework mode) or a data-mode loader that throws a 404 response. See 404 Pages and Catch-All Routes.

10. What is the difference between <Navigate>, useNavigate and redirect?

All three change the location, but at different moments. <Navigate> is a component that redirects when it renders. useNavigate() returns a function for event handlers (after a save, for example). redirect() returns a redirect response from a loader or action, before any component renders. Prefer redirect in data mode, because it avoids a flash of the wrong page; avoid calling navigate inside an effect when a loader can do the job. See Redirects with Navigate and useNavigate.

11. What does the replace option do?

It overwrites the current history entry instead of adding a new one. Use it for redirects (login, old URLs, an index redirect) so the back button does not return to a URL that redirects again and traps the user in a loop.

Nested routes and layouts

12. How do nested routes and <Outlet> work?

A child route's path is relative to its parent, and the parent's element decides where the child appears by rendering <Outlet />. The URL /account/security therefore renders <AccountLayout> with <Security> inside it. Layouts stay mounted when you move between their children, so their state (and the scroll position of a sidebar) survives. See Nested Routes and Outlet.

flowchart TD
  U["URL: /account/security"] --> R["Root layout"]
  R --> A["Account layout"]
  A --> S["Security page"]
  R -. "Outlet" .-> A
  A -. "Outlet" .-> S

Each layout renders an Outlet where the next matched route appears.

13. What is a layout route or pathless route?

A route with an element but no path. It adds structure (a shared header, a guard, an error boundary) without adding a URL segment. Several unrelated routes can share one layout, and different groups of routes can use different layouts. See Layout Routes and Pathless Routes.

14. How do you pass data from a layout to its children?

Three options. Render <Outlet context={value} /> and read it with useOutletContext() in children, which suits small values that only that layout's children need. Use a loader on the parent and read it with useRouteLoaderData(routeId) from a child. Use ordinary React context for app-wide values. See Passing Data Down with Outlet Context.

By default a relative to (no leading slash) resolves against the route that renders the link, not the full URL. A link to=".." inside a route goes up one route level, which is not always one URL segment. Pass relative="path" to resolve against URL segments instead. Absolute links (/settings) are the safe choice when in doubt. See Relative Links and Relative Routing.

Params, search params and state

16. How do you read URL parameters, and what type are they?

Define a dynamic segment (/posts/:postId) and call useParams(), or read params in a loader. Values are always strings (or undefined for optional segments), so convert and validate them (Number(params.postId)), and treat an invalid value as a 404. A splat route puts the rest of the path in params["*"]. See Dynamic Segments and useParams.

17. When do you use search params, and how does useSearchParams work?

Use the query string for state that should survive a refresh and be shareable: filters, sort order, page number, selected tab. useSearchParams() returns [searchParams, setSearchParams], like useState, where searchParams is a standard URLSearchParams. Updating it navigates, so loaders that depend on it run again. Use replace for rapid changes such as typing in a search box so the history is not flooded. See Search Params and useSearchParams and Putting UI State in the URL.

18. What is location state, and when is it a bad idea?

navigate(to, { state }) or <Link state={...}> attaches a value to the history entry. It is read with useLocation().state. It is good for hints that only make sense for this navigation, such as the from page after a login redirect. It is not shareable and may be missing (a pasted URL has no state), so never put information there that the page cannot work without. See useLocation and Navigation State.

Data mode

19. What is a loader and why is it better than fetching in useEffect?

A loader is a function on a route that runs before the route renders and whose result is read with useLoaderData(). All loaders for the matched route chain run in parallel, so you avoid the waterfall where a parent renders, fetches, and only then lets the child start fetching. There is no loading flag to manage inside the component, race conditions between navigations are handled (a stale result is discarded), and errors reach an error element. See Loaders.

JSX
// Real React Router v7 (data mode), read-only
import { createBrowserRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';

const router = createBrowserRouter([
  {
    path: '/',
    Component: Root,
    children: [
      { index: true, Component: Home },
      {
        path: 'posts/:postId',
        Component: Post,
        loader: async ({ params }) => {
          const response = await fetch(`/api/posts/${params.postId}`);
          if (!response.ok) {
            throw new Response('Not found', { status: 404 });
          }
          return response.json();
        },
      },
    ],
  },
]);

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

20. How do actions and <Form> work, and what is revalidation?

<Form method="post"> submits to the route's action through the router instead of the browser: no page reload, and the router can show pending state. The action receives a request, reads await request.formData(), performs the mutation and returns data or a redirect. After an action finishes, the router revalidates: it calls the loaders of the current page again so the screen shows fresh data without manual refetching. You can tune this with shouldRevalidate. See Actions and Form and Revalidation and Caching.

The demo is a stand-in with the same lifecycle. Add an item and read the log: the action runs first, then both loaders run again.

An action followed by revalidation

The first load logs navigation: root loader and navigation: items loader. After you press the button the log gains action: add coffee, then revalidate: root loader and revalidate: items loader, and the list shows tea and coffee. In the real router the same happens automatically, and useNavigation().state goes idle, submitting, loading, idle.

21. What is useFetcher and when do you reach for it?

A fetcher lets you call a loader or action without navigating: toggling a favorite, a "like" button, a search-as-you-type box, a row delete in a list. Each fetcher has its own state and formData, so several can run at once, which also makes optimistic UI easy (render from fetcher.formData while the request is pending). Use <Form> when the submit should change the URL and fetcher.Form when it should not. See useFetcher and Inline Mutations and Pending and Optimistic UI.

22. How does error handling work in data mode?

If a loader, action or component throws, React Router renders the route's error element (errorElement, or the ErrorBoundary property) instead of the route, and it picks the nearest boundary up the route tree, so one broken child does not blank the whole page. Inside it, useRouteError() gives the thrown value, and isRouteErrorResponse(error) tells you whether it was a thrown Response (with status and data) or an unexpected exception. Throwing a 404 response from a loader is the idiomatic way to show "post not found". See Error Boundaries and Error Elements.

Production topics

23. How do you implement protected routes, and are they secure?

Build a pathless guard layout route that checks the session and either renders <Outlet /> or redirects to /login with the wanted location in state (or, in data mode, throws redirect from a loader). A client-side guard is a user-experience feature, not security: the code and data you ship to the browser can be inspected and altered. Every API endpoint must verify the session and permissions itself and answer 401 or 403. See Protected Routes and Auth Redirects.

24. How do you code-split routes?

In data mode give a route a lazy function that dynamically imports its module (lazy: () => import('./routes/reports')), so the bundle for that route downloads only when someone navigates there; in framework mode the tooling splits every route module for you. Because the router resolves the lazy module before rendering the route, you avoid the layout flash that a React.lazy fallback can cause. Preloading on link hover hides the delay further. See Lazy Routes and Code Splitting.

25. How do you test components that use the router?

Components that call router hooks need a router above them, so tests wrap them in createMemoryRouter with <RouterProvider> (or MemoryRouter in declarative mode), set initialEntries to the URL under test, and then interact with the rendered output using Testing Library: click a link and assert on the new screen, submit a form and assert on the result. createRoutesStub is handy for one component with fake loaders and actions. Test behavior (what the user sees), not router internals. See Testing Routes and Components.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two routes match the URL /users/new: /users/:id and /users/new. Which one renders?

    React Router ranks matches by specificity, not by declaration order. A static segment beats a dynamic segment, so /users/new wins.
  2. 2. What happens after a route action finishes in data mode?

    Revalidation is automatic after an action. The router reruns the active loaders (you can narrow this with shouldRevalidate).
  3. 3. Why are client-side route guards not enough to protect private data?

    A guard decides what the UI shows. Anyone can bypass it, so APIs must check the session and permissions and answer 401 or 403.
  4. 4. When is useFetcher the better choice than <Form>?

    A fetcher runs a request without a navigation and has its own state, so many can be active at once. <Form> is for submits that navigate.
  5. 5. Which parameter value type does useParams give you for /posts/:postId?

    URL segments are text. Convert and validate them yourself and treat invalid values as not found.

Summary

  • Know the three modes (declarative, data, framework) and that each adds to the previous one; v7 absorbed the Remix v2 features into react-router.
  • Matching is ranked by specificity; nested routes compose layouts through <Outlet />, and pathless routes add structure without adding URL segments.
  • Params are strings, search params hold shareable UI state, and location state is a non-shareable hint.
  • Loaders run in parallel before render, actions mutate and then trigger revalidation, and fetchers do both without navigating.
  • Errors go to the nearest error element; a thrown Response is the idiomatic way to signal a 404.
  • Guards improve the user experience; only the server protects data.

Next: React Router Cheat Sheet