React Interview Questions (Part 5): Routing

Yusuf UysalYusuf Uysal
5 min read

1. How does routing work in React using React Router?

In React Router v6, routing is more efficient with a new API that introduces createBrowserRouter for setting up your routes. This allows us to handle client-side routing seamlessly, enabling navigation without full page reloads.

Key Parts:

  1. createBrowserRouter: This replaces the need for <BrowserRouter> from previous versions and is now the main function for defining routes.

  2. RouterProvider: Wraps your application and enables the defined routes to work.

  3. Route Definitions: You define your paths and the corresponding components in an array of route objects.

Example in React Router v6:

import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Home from './Home';
import About from './About';

const router = createBrowserRouter([
  { path: "/", element: <Home /> },
  { path: "/about", element: <About /> }
]);

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

In this example:

  • createBrowserRouter: Sets up your routes in an array. Each object in the array defines a path and the element to render.

  • RouterProvider: Wraps the entire app to provide routing capabilities.

  • Dynamic routing: The router will render the correct component when the URL matches the specified path.

When the user visits /, the Home component is shown. When they go to /about, the About component is rendered. All this happens without a full page reload, making navigation smooth and fast.

2. What are dynamic routes, and how do you implement them in React Router?

Dynamic routes in React Router v6 allow you to create routes with dynamic values in the URL. These routes are useful for paths where a specific part of the URL changes, such as user profiles (/user/:id) or product pages (/product/:productId).

In React Router v6, dynamic segments are defined using a : followed by the parameter name in the path. This allows you to capture that part of the URL and access it within your component using the useParams hook.

Example:

Let’s say you want to display a user profile based on their user ID.

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

const router = createBrowserRouter([
  {
    path: "/user/:id",  // ":id" is a dynamic segment in the URL
    element: <UserProfile />,
  }
]);

function UserProfile() {
  const { id } = useParams();  // Extract the dynamic value from the URL
  return <h1>User ID: {id}</h1>; 
}

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

How it Works:

  • The path in the route is /user/:id, where :id is a dynamic parameter. This means the part after /user/ in the URL will be treated as a variable.

  • Inside the UserProfile component, the useParams hook is used to extract this dynamic id from the URL.

  • You can then use this dynamic id to fetch specific data (e.g., user details) or perform other operations.

Example URL:

  • /user/123 will render the UserProfile component and display "User Profile for ID: 123".

  • /user/456 will display "User Profile for ID: 456".

Dynamic routes are essential for building flexible and scalable applications, as they allow you to create dynamic URLs that can adjust based on your data or user input.

3. How do you handle redirects using useNavigate in React Router?

In React Router v6, the useNavigate hook replaces the older useHistory hook for programmatic navigation. It’s a simple yet powerful tool to redirect users to different routes based on conditions, such as after a form submission, a successful login, or some other user action.

How it works:

useNavigate returns a function that allows you to programmatically navigate to a specific route. You can call this function inside your components to perform redirects.

Example:

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

function Home() {
  const navigate = useNavigate();
  return <button onClick={() => navigate("/dashboard")}>Go to Dashboard</button>;
}

In this example:

  • The useNavigate hook is used inside the Home component.

  • On clicking the "Login" button, the user is redirected to the /dashboard route programmatically by calling navigate("/dashboard").

When to use it:

  • After form submissions: Redirect to a success page.

  • Conditional navigation: Redirect based on user roles, authentication status, etc.

  • Programmatic redirects: Navigate based on events or conditions, without requiring user interaction with a link.

4. How do nested routes work in React Router?

Nested routes allow you to organize your app better by grouping related routes under a parent route. For example, if you have a dashboard with subpages like Users and Settings, you can nest these routes under the main dashboard route.

Example:

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

// Parent component for the Dashboard
function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Outlet /> {/* Renders child routes here */}
    </div>
  );
}

// Child component for Users page
function Users() {
  return <h2>Users Page</h2>;
}

// Define the routes with a nested route
const router = createBrowserRouter([
  {
    path: "/dashboard",
    element: <Dashboard />,
    children: [
      { path: "users", element: <Users /> }, 
    ],
  },
]);

function App() {
  return <RouterProvider router={router} />;
}
  • <Outlet />: This is where child routes will be rendered inside the parent component.

5. How do you handle error handling in React Router?

In React Router v6, error handling can be done using a few simple techniques, like creating fallback routes and custom error components.

  1. Error Boundaries: You can display a custom error message when an error occurs during routing by using an errorElement in your route definition.

  2. 404 Handling: A * path is used as a fallback to catch any unmatched routes and display a “404 - Not Found” page.

Example:

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

function NotFound() {
  return <h1>404 - Page Not Found</h1>;
}

function ErrorBoundary() {
  const error = useRouteError();
  return <p>{error.statusText || "Something went wrong!"}</p>;
}

const router = createBrowserRouter([
  {
    path: "/",
    element: <HomePage />,
    errorElement: <ErrorBoundary />, // Handles route errors
  },
  { path: "*", element: <NotFound /> }, // Handles 404 errors
]);

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

A Note on Modern Web Development with Next.js

While understanding how routing works with React Router is crucial for interviews and for understanding client-side navigation in React, many modern applications now use frameworks like Next.js. With its built-in file-based routing system, Next.js simplifies routing and reduces the need for manual configuration. This approach is more common in modern web development.

However, knowing React Router can still be very valuable for building React applications without a framework, and it's a common interview topic. To explore more routing features and understand the finer details, I recommend checking out the official React Router documentation.

0
Subscribe to my newsletter

Read articles from Yusuf Uysal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yusuf Uysal
Yusuf Uysal

𝗗𝗿𝗶𝘃𝗲𝗻 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 with extensive experience in JavaScript, React.js, and Next.js. I help companies enhance user engagement and deliver high-performance web applications that are responsive, accessible, and visually appealing. Beyond my technical skills, I am a 𝗰𝗼𝗹𝗹𝗮𝗯𝗼𝗿𝗮𝘁𝗶𝘃𝗲 𝘁𝗲𝗮𝗺 𝗽𝗹𝗮𝘆𝗲𝗿 who thrives in environments that value continuous learning and innovation. I enjoy projects where I can leverage my expertise in 𝗿𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝘃𝗲 𝗱𝗲𝘀𝗶𝗴𝗻, 𝗯𝗿𝗼𝘄𝘀𝗲𝗿 𝗰𝗼𝗺𝗽𝗮𝘁𝗶𝗯𝗶𝗹𝗶𝘁𝘆, 𝗮𝗻𝗱 𝘄𝗲𝗯 𝗽𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 to deliver seamless user experiences. I get excited about opportunities where I can contribute to creating dynamic, user-focused applications while working closely with cross-functional teams to drive impactful results. I love connecting with new people, and you can reach me at yusufuysal.dev@gmail.com.