React Router: Declarative vs. Programmatic Routing

Table of contents

No heading

No headings in the article.

Method 1: Declarative Syntax (BrowserRouter, Routes, Route)

Key Features:

  • Declarative: Define routes directly within JSX, making code more readable and maintainable.

  • Simple: Ideal for most React applications with straightforward routing needs.

  • Commonly used: Widely adopted approach in React Router v6 and later.

Example:

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</BrowserRouter>

Method 2: Router Configuration API (createBrowserRouter, RouterProvider)

Key Features:

  • Programmatic: Build routes programmatically for greater control and customization.

  • Advanced Features: Supports data fetching, error handling, code splitting, and more.

  • Data Fetching: Simplify data fetching with loader and action options.

  • Error Handling: Define custom error pages with errorElement.

JavaScript

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
    loader: homeLoader, // Function to fetch data for Home
    action: homeAction, // Function to handle data fetching results
    errorElement: <ErrorBoundary />, // Custom error boundary
  },
]);

<React.StrictMode>
  <RouterProvider router={router} />
</React.StrictMode>

content_copy

When to Use Each:

  • Declarative Syntax (Method 1): Best for most standard React applications with uncomplicated routing needs.

  • Router Configuration API (Method 2): Prefer this for:

    • Advanced features like data fetching, code splitting, and custom error handling.

    • Granular control over route configuration.

Key Points:

  • Both methods create a React Router context for your application.

  • The RouterProvider component makes the router instance available to other components.

  • Data fetching and error handling are built-in with the Router Configuration API.

Additional Considerations:

  • React Router v5 and earlier heavily relied on the Router Configuration API.

  • React Router v6 introduced the declarative syntax as the preferred approach for most cases.