React Router


React Router Interview with follow-up questions

1. What is React Router and why is it important in React applications?

React Router is the de-facto routing library for React, providing declarative, client-side navigation: it maps URLs to components so you can build single-page apps with multiple views and browser history support — back/forward, deep links, and bookmarkable URLs — without full page reloads.

Why it matters: React itself has no routing; React Router fills that gap with /, navigation (`,useNavigate), URL params (useParams`), and nested/layout routes.

Current version context (2026): React Router v7 merged with Remix and now offers three modes:

  • Declarative mode – the classic + for simple SPAs.
  • Data modecreateBrowserRouter + RouterProvider with loaders and actions for data fetching/mutations tied to routes.
  • Framework mode – a full-stack setup with SSR, file-based routes, and code-splitting.

It's one of the two main ways to do routing in the React ecosystem, alongside framework routers like Next.js's App Router.

↑ Back to top

Follow-up 1

Can you explain how React Router differs from conventional routing?

React Router differs from conventional routing in a few ways:

  1. Declarative Routing: React Router uses a declarative approach, where routes are defined as components and rendered based on the current URL. This allows for a more intuitive and flexible way of handling navigation.

  2. Single-Page Applications: React Router is designed specifically for single-page applications, where the entire application is loaded once and subsequent views are rendered dynamically without a full page reload.

  3. Component-Based Routing: React Router allows for routing based on components, rather than URLs. This means that different components can be rendered based on the URL, providing a more modular and reusable approach to routing.

Follow-up 2

What are some of the main components provided by React Router?

React Router provides several main components for handling routing in React applications:

  1. BrowserRouter: This component wraps the entire application and provides the routing functionality. It uses HTML5 history API to keep the UI in sync with the URL.

  2. Route: This component defines a route and the component to render when the URL matches the route. It can also pass props to the rendered component.

  3. Switch: This component is used to render only the first matching route inside it. It is useful for handling 404 or not found pages.

  4. Link: This component is used to create links between different routes. It automatically updates the URL and triggers the rendering of the corresponding component.

  5. Redirect: This component is used to redirect the user to a different route. It can be used for authentication or other conditional redirects.

Follow-up 3

How does React Router handle 404 or not found pages?

React Router provides a component called Switch that is used to handle 404 or not found pages. The Switch component renders only the first matching route inside it. By placing a Route component with a path of '*' (wildcard) at the end of the Switch, it acts as a catch-all route that matches any URL that hasn't been matched by previous routes. This allows for the rendering of a custom 404 or not found page when no other routes match the current URL.

2. How do you set up routing in a React application using React Router?

For a simple SPA, install react-router-dom, wrap the app in a router, and declare routes with / (note: Switch was replaced by Routes in v6, and component={...} by element={...}):

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (

      Home About

        } />
        } />
        } />
        } />


  );
}

For apps that need data loading/mutations, use data mode (React Router v7):

import { createBrowserRouter, RouterProvider } from "react-router-dom";

const router = createBrowserRouter([
  { path: "/", element: , loader: homeLoader },
  { path: "/users/:id", element: , loader: userLoader },
]);

;

This unlocks route loaders, actions, and built-in error boundaries. Read params with useParams, navigate with useNavigate.

↑ Back to top

Follow-up 1

What is the significance of the 'exact' prop in React Router?

The 'exact' prop in React Router is used to ensure that a route is only matched if the path is an exact match. By default, React Router uses a prefix matching algorithm, which means that if the path of a route is a prefix of the current URL, the route will be considered a match and rendered. However, if you want to render a route only when the path is an exact match, you can use the 'exact' prop.

For example, consider the following routes:



If the current URL is '/', both the Home and About components will be rendered because the path '/' is a prefix of '/about'. However, if you add the 'exact' prop to the Home route like this:


Only the Home component will be rendered when the current URL is '/'.

Follow-up 2

How can you pass parameters to routes in React Router?

You can pass parameters to routes in React Router by using the ':' syntax in the route path. The value of the parameter will be accessible in the component rendered by the route through the 'match' prop.

Here's an example of how to pass parameters to routes in React Router:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';

const App = () => {
  return (



  );
};

const User = ({ match }) => {
  const userId = match.params.id;
  // Use the userId to fetch user data or perform other operations
  return <div>User ID: {userId}</div>;
};

export default App;

In this example, the route path '/user/:id' will match any URL that starts with '/user/' followed by a parameter. The value of the parameter will be accessible in the User component through the 'match.params.id' property.

Follow-up 3

Can you explain how nested routing works in React Router?

Nested routing in React Router allows you to define routes within routes, creating a hierarchy of components. This can be useful for building complex applications with multiple levels of navigation.

To set up nested routing in React Router, you can define child routes within the component rendered by a parent route. The child routes will be rendered within the parent component, allowing you to create nested navigation structures.

Here's an example of how to set up nested routing in React Router:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';

const App = () =&gt; {
  return (



  );
};

const Home = () =&gt; {
  return (
    <div>
      <h1>Home</h1>


    </div>
  );
};

const About = () =&gt; {
  return <h2>About</h2>;
};

const Contact = () =&gt; {
  return <h2>Contact</h2>;
};

export default App;

In this example, the Home component is rendered for the '/' route. Within the Home component, there are two child routes: '/about' and '/contact'. When the URL matches one of these child routes, the corresponding component (About or Contact) will be rendered within the Home component.

3. What is the difference between 'BrowserRouter' and 'HashRouter' in React Router?

Both render UI based on the URL; the difference is how the URL is encoded:

  • BrowserRouter uses the HTML5 History API (pushState), producing clean URLs like example.com/about. This is the standard choice. It requires the server to be configured to return your index.html for any path (a "rewrite to index"), otherwise a direct visit/refresh of /about 404s.

  • HashRouter keeps routing in the URL hash: example.com/#/about. The part after # never reaches the server, so it works on static hosts with no rewrite support and very old environments — at the cost of uglier URLs and weaker SEO.

BrowserRouter HashRouter
URL /about /#/about
Needs server rewrite yes no
SEO-friendly yes weaker

Use BrowserRouter by default; choose HashRouter only when you can't configure server-side routing (e.g. pure static file hosting).

↑ Back to top

Follow-up 1

In what scenarios would you use HashRouter over BrowserRouter?

You would use 'HashRouter' over 'BrowserRouter' in scenarios where you need to support older browsers or environments that do not support the HTML5 history API. 'HashRouter' is a fallback option that ensures your application can still handle routing even in these environments. Additionally, if you are deploying your application to a static file server that only serves static files, 'HashRouter' is a better choice as it does not require any server-side configuration to handle URL routing.

Follow-up 2

How does the 'history' prop work in React Router?

The 'history' prop in React Router allows you to customize the way routing is handled. It provides a history object that contains methods and properties for manipulating the browser URL and navigating between different routes.

By default, React Router creates a history object based on the router type you are using ('BrowserRouter' or 'HashRouter'). However, you can also create a custom history object and pass it as the 'history' prop to the router component.

The 'history' object provides methods like 'push', 'replace', and 'goBack' to navigate between routes programmatically. It also provides properties like 'location' and 'match' to access information about the current route.

Using the 'history' prop, you can have more control over how routing is handled in your React application and implement custom navigation logic if needed.

4. How do you programmatically navigate to another route using React Router?

Use the useNavigate hook (this replaced the old v5 useHistory/history.push):

import { useNavigate } from "react-router-dom";

function LoginButton() {
  const navigate = useNavigate();

  const handleLogin = async () =&gt; {
    await login();
    navigate("/dashboard");          // go to a route
    // navigate(-1);                  // go back
    // navigate("/dashboard", { replace: true, state: { from: "login" } });
  };

  return Log in;
}

Options:

  • A path string navigates forward; a number moves through history (navigate(-1) = back).
  • { replace: true } replaces the current entry (no back-button entry) — handy after auth.
  • { state } passes data to the destination, read with useLocation().state.

For declarative navigation (e.g. redirects in JSX) use the `component. Note:useHistoryanduseNavigate's callback are React Router v6/v7 APIs; v5'suseHistory` is deprecated.

↑ Back to top

Follow-up 1

What is the use of 'withRouter' in React Router?

'withRouter' is a higher-order component (HOC) provided by React Router. It is used to access the 'history', 'location', and 'match' props of the current route outside of a component that is rendered by a 'Route' component.

Here is an example of how you can use 'withRouter' to access the 'history' object and navigate to a different route:

import { withRouter } from 'react-router-dom';

function MyComponent({ history }) {
  function handleClick() {
    history.push('/another-route');
  }

  return (
    Go to Another Route
  );
}

export default withRouter(MyComponent);

Follow-up 2

How can you use the 'history' object to navigate to a different route?

To use the 'history' object to navigate to a different route, you can call its 'push' method and pass the desired route path as an argument.

Here is an example of how you can use the 'history' object to navigate to a different route:

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  function handleClick() {
    history.push('/another-route');
  }

  return (
    Go to Another Route
  );
}

5. What is 'Link' and 'NavLink' in React Router and how are they different?

Both render accessible navigation as real anchor (<a>) tags that update the URL via client-side routing (no full reload), but NavLink is a Link that knows whether it's "active" (matches the current URL), which is ideal for nav menus.

import { Link, NavLink } from "react-router-dom";

About

 (isActive ? "active" : "")}
&gt;
  About

Key difference: NavLink passes an isActive (and isPending in data mode) flag to its className/style/children when given a function, so you can highlight the current route. In React Router v7, className/style accept that render-prop form (the old activeClassName prop was removed in v6).

Use Link for ordinary links and NavLink for navigation items that should reflect the active route.

↑ Back to top

Follow-up 1

How can you style the active route using NavLink?

To style the active route using 'NavLink', you can use the 'activeClassName' and 'activeStyle' props. The 'activeClassName' prop allows you to specify a CSS class name that will be applied to the 'NavLink' component when its route is active. The 'activeStyle' prop allows you to specify inline CSS styles that will be applied to the 'NavLink' component when its route is active.

Example:

import { NavLink } from 'react-router-dom';

Home

In the above example, when the route '/home' is active, the 'NavLink' component will have the 'active' class applied to it.

Follow-up 2

What are the advantages of using 'Link' or 'NavLink' over traditional anchor tags in React Router?

There are several advantages of using 'Link' or 'NavLink' over traditional anchor tags in React Router:

  1. Prevents page refresh: When using anchor tags, clicking on a link will cause a full page refresh. 'Link' and 'NavLink' components in React Router prevent this behavior and instead update the URL and render the appropriate component without refreshing the entire page.

  2. Supports single-page applications: React Router is designed for building single-page applications (SPAs) where the content is dynamically loaded without refreshing the page. 'Link' and 'NavLink' components are specifically designed to work with React Router and provide a seamless navigation experience within an SPA.

  3. Handles routing internally: 'Link' and 'NavLink' components handle the routing internally, allowing you to define routes and navigate between them without manually managing the URL or handling the navigation logic yourself.

  4. Provides additional functionality: 'NavLink' component provides additional styling and functionality for the active route, making it easier to highlight the current route and provide visual feedback to the user.

Overall, using 'Link' or 'NavLink' components in React Router provides a more efficient and user-friendly way to handle navigation in a React application compared to traditional anchor tags.

Live mock interview

Mock interview: React Router

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.