The useMatch hook is used to determine if the current URL matches a given path pattern.
How to use useMatch hook in React Router
Key takeaways:
The
useMatchhook offers an efficient way to match routes dynamically, reducing the complexity of routing logic and enhancing code maintainability.By using the
useMatchhook, you can conditionally render components based on specific URL patterns, improving the user experience.The
useMatchhook 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 hookconst match = useMatch(pattern);
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 returnsnull.
How does the useMatch work?
When you call the
useMatchhook with a path as its argument, React Router internally compares the current location with the provided path.If the current location matches the path, the
useMatchhook returns amatchobject. This object contains several properties that provide information about the match.params: An object containing key-value pairs for dynamic segments, e.g.,{ id: '12' }for/user/:id.pathname: It contains the full URL path that was matched. It shows the actual path the user visited.pathnameBase: The base path that was matched without any trailing parameters or nested routes.pattern: It describes the path pattern that was matched. It includes the following sub-properties:path: The exact pattern used to match the route (e.g.,/user/:id).caseSensitive: It is a boolean that indicates whether the match is case-sensitive. Iffalse, both/Userand/userwould match the same pattern. Iftrue, only the exact casing will match.end: It is a boolean that determines if the match must be exact. Iftrue, the match succeeds only if the entire path matches. Iffalse, partial matches are allowed.
If the current location doesn’t match the path, the
useMatchhook returnsnull. 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-dompackage. These includeRoutes,BrowserRouter,Route,useMatch,Outlet, andNavLink, which are used for setting up routing in the application.Lines 11–17: The
Indexcomponent is a functional component that represents the home page. It renders a heading (<h2>) with the text “Home Page.”Lines 19–32: The
Navcomponent 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 aNavLinkcomponent. TheseNavLinkcomponents represent the navigation links for the home, profile, and about pages. TheOutletcomponent is also rendered, which acts as a placeholder for the content of the current route.Lines 34–62: The
ProfileandAboutcomponents are functional components that represent the profile and about page. They use theuseMatchhook to check if the current route matches the path/profileand/about. If there’s a match, it renders a<pre>tag with the stringified JSON representation of thematchobject.Lines 64–76: The
Appcomponent wraps the routing components inside aBrowserRoutercomponent, enabling client-side routing in the application. Inside theRoutescomponent, there’s a top-levelRoutecomponent with theelementprop set to<Nav />, indicating that theNavcomponent will always be rendered. Within thisRoute, there are nestedRoutecomponents.The first nested
Routehas theindexprop set, representing the index or home route. It renders theIndexcomponent.The second and third nested
Routecomponents have thepathprop set to/profileand/about, respectively. They render theProfileandAboutcomponents 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-dompackage. These includeRoutes,BrowserRouter,Route,useMatch,Outlet, andNavLink, which are used for setting up routing in the application.Lines 11–17: The
Indexcomponent is a functional component that represents the home page. It renders a heading (<h2>) with the text “Home Page.”Lines 19–36: The
UserProfilecomponent is a functional component that defines the user profile page. It uses theuseMatchhook to match the path/user/:id.If the route matches (e.g.,
/user/1), the hook extracts theidparameter and renders it within the component along with thematchobject.If the route doesn’t match, a message indicating “User not found” is displayed instead.
Lines 38–54: The
Appcomponent sets up the routes and navigation for the user profile pages.We define multiple
NavLinkcomponents directing the user to the/user/1, and/user/2paths.The
Routecomponent defines the/user/:idpath as a dynamic route. When the path matches, theUserProfilecomponent 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
The primary strength of the
useMatchhook 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.With the
useMatchhook, 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.The
useMatchhook also supports parameterized paths. By defining dynamic segments in the path using the:paramNamesyntax, you can extract parameter values from the URL using thematch.paramsobject. This capability simplifies working with dynamic routes where values vary, such as user profiles or product pages.React Router’s
useMatchhook 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
The
useMatchhook is less effective when working with deeply nested routes. For such scenarios, you might need to combine it with other hooks likeuseParamsoruseLocation, adding complexity to your code.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?
Can I use useMatch with nested routes?
Why does the match object in React Router v6 not include isExact?
Free Resources