How to use useMatch hook in React Router

Key takeaways:

  • The useMatch hook offers an efficient way to match routes dynamically, reducing the complexity of routing logic and enhancing code maintainability.

  • By using the useMatch hook, you can conditionally render components based on specific URL patterns, improving the user experience.

  • The useMatch hook supports dynamic segments in paths (e.g., /blog/:id) and extracts parameters easily for component use which is ideal for user profiles or product pages.

The useMatch hook

The useMatch hook in React Router is a powerful tool that enables us to determine if the current URL matches a particular path. It provides a straightforward way to conditionally render components or perform logic based on the matched path.

The syntax to define a useMatch hook is as follows:

import { useMatch } from 'react-router-dom'; // Import the hook
const match = useMatch(pattern);
Syntax for useMatch hook

In the syntax above, we have the following:

  • pattern: This is the path pattern you want to match against the current URL. It can also include dynamic segments (e.g., /product/:id).

  • match: If the current URL matches the pattern, the hook returns an object with details about the match. If not, it returns null.

How does the useMatch work?

  1. When you call the useMatch hook with a path as its argument, React Router internally compares the current location with the provided path.

  2. If the current location matches the path, the useMatch hook returns a match object. This object contains several properties that provide information about the match.

    1. params: An object containing key-value pairs for dynamic segments, e.g., { id: '12' } for /user/:id.

    2. pathname: It contains the full URL path that was matched. It shows the actual path the user visited.

    3. pathnameBase: The base path that was matched without any trailing parameters or nested routes.

    4. pattern: It describes the path pattern that was matched. It includes the following sub-properties:

      1. path: The exact pattern used to match the route (e.g., /user/:id).

      2. caseSensitive: It is a boolean that indicates whether the match is case-sensitive. If false, both /User and /user would match the same pattern. If true, only the exact casing will match.

      3. end: It is a boolean that determines if the match must be exact. If true, the match succeeds only if the entire path matches. If false, partial matches are allowed.

  3. If the current location doesn’t match the path, the useMatch hook returns null. This can be useful for rendering fallback content or handling unmatched routes.

Learn more the React Router, by trying this project: Create a Website with Dynamic Routing Using React Router.

Example 1: Using the useMatch hook for static routes

Let’s take a look at how to use the useMatch() hook for static routes.

Code explanation

  • Lines 2–9: We import the necessary components and hooks from the react-router-dom package. These include Routes, BrowserRouter, Route, useMatch, Outlet, and NavLink, which are used for setting up routing in the application.

  • Lines 1117: The Index component is a functional component that represents the home page. It renders a heading (<h2>) with the text “Home Page.”

  • Lines 19–32: The Nav component is a functional component that represents the navigation menu. It renders a header containing an unordered list (<ul>). Inside the list, there are three list items (<li>), each containing a NavLink component. These NavLink components represent the navigation links for the home, profile, and about pages. The Outlet component is also rendered, which acts as a placeholder for the content of the current route.

  • Lines 34–62: The Profile and About components are functional components that represent the profile and about page. They use the useMatch hook to check if the current route matches the path /profile and /about. If there’s a match, it renders a <pre> tag with the stringified JSON representation of the match object.

  • Lines 64–76: The App component wraps the routing components inside a BrowserRouter component, enabling client-side routing in the application. Inside the Routes component, there’s a top-level Route component with the element prop set to <Nav />, indicating that the Nav component will always be rendered. Within this Route, there are nested Route components.

    • The first nested Route has the index prop set, representing the index or home route. It renders the Index component.

    • The second and third nested Route components have the path prop set to /profile and /about, respectively. They render the Profile and About components based on the matching paths.

Implement React Router hooks in a real world application in this project: Build a Stock Market App Using React and Chart.js.

Example 2: Using the useMatch for dynamic routes

Let’s take a look at how to use the useMatch() hook for dynamic routes.

Explanation

  • Lines 2–9: We import the necessary components and hooks from the react-router-dom package. These include Routes, BrowserRouter, Route, useMatch, Outlet, and NavLink, which are used for setting up routing in the application.

  • Lines 1117: The Index component is a functional component that represents the home page. It renders a heading (<h2>) with the text “Home Page.”

  • Lines 19–36: The UserProfile component is a functional component that defines the user profile page. It uses the useMatch hook to match the path /user/:id.

    • If the route matches (e.g., /user/1), the hook extracts the id parameter and renders it within the component along with the match object.

    • If the route doesn’t match, a message indicating “User not found” is displayed instead.

  • Lines 38–54: The App component sets up the routes and navigation for the user profile pages.

    • We define multiple NavLink components directing the user to the /user/1, and /user/2 paths.

    • The Route component defines the /user/:id path as a dynamic route. When the path matches, the UserProfile component is rendered, displaying the user ID extracted from the URL.

Explore advance usage of React Router in this project: Build an Image Sharing App with MERN Stack.

Advantages of the useMatch hook

  1. The primary strength of the useMatch hook is its ability to compare the current location path with a specified path pattern. It allows you to determine if the current URL matches a particular path, providing you with flexibility in handling different routes and rendering components accordingly.

  2. With the useMatch hook, you can implement dynamic routing logic based on the matched path. It enables you to conditionally render components, apply different styles, fetch data, or perform other actions based on the current URL. This flexibility is valuable when building complex navigation systems or handling specific routes in your application.

  3. The useMatch hook also supports parameterized paths. By defining dynamic segments in the path using the :paramName syntax, you can extract parameter values from the URL using the match.params object. This capability simplifies working with dynamic routes where values vary, such as user profiles or product pages.

  4. React Router’s useMatch hook provides fine-grained control over routing behavior. By conditionally rendering components based on the match result, you can create different layouts, handle authentication or authorization, or trigger specific actions depending on the current URL. This level of control contributes to building robust and dynamic routing systems.

Disadvantages of the useMatch Hook

  1. The useMatch hook is less effective when working with deeply nested routes. For such scenarios, you might need to combine it with other hooks like useParams or useLocation, adding complexity to your code.

  2. Since the useMatch hook is specific to React Router, it couples your application logic to the library, making migrations to other routing libraries more challenging.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the useMatch hook used for?

The useMatch hook is used to determine if the current URL matches a given path pattern.


Can I use useMatch with nested routes?

Yes, you can use it with nested routes. For instance, /dashboard/settings can match specific child routes by configuring nested paths within the Routes component.


Why does the match object in React Router v6 not include isExact?

React Router v6 enforces exact matching by default. This removes the need for the isExact property, which was used in earlier versions (v5) to indicate whether the match was exact.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved