Design Converter
Education
Last updated on Mar 21, 2025
•12 mins read
Last updated on Mar 21, 2025
•12 mins read
Software Development Executive - II
React Router is a staple for navigation in React apps. One of its many features is the useRouteMatch hook which gives developers a way to access routing data.
This blog will cover how useRouteMatch works and where it fits in the React Router landscape.
The useRouteMatch hook is part of the React Router DOM library's collection of hooks designed to give components access to routing information. This hook attempts to match the current URL against a provided path pattern and returns valuable match data.
1import { useRouteMatch } from 'react-router-dom'; 2 3function ProfilePage() { 4 // Using useRouteMatch without arguments to match current route 5 const match = useRouteMatch(); 6 7 console.log(match); // Logs the match object with information about the current route 8 9 return ( 10 <div> 11 <h2>Current Path: {match.path}</h2> 12 <p>URL: {match.url}</p> 13 </div> 14 ); 15}
When you use the useRouteMatch hook, it returns a match object containing information about how the current URL matches the route path. This match object has several properties that help you understand the relationship between your route component and the URL.
The match object returned by useRouteMatch contains the following properties:
path - A string representing the route path pattern used for matching
url - The matched portion of the URL
isExact - Boolean indicating if the match is exact
params - An object containing any URL parameters extracted from the path
1import { useRouteMatch } from 'react-router-dom'; 2 3function UserProfile() { 4 // Match against a specific path 5 const match = useRouteMatch('/users/:userId'); 6 7 if (!match) { 8 return <div>This route doesn't match</div>; 9 } 10 11 return ( 12 <div> 13 <h2>User ID: {match.params.userId}</h2> 14 <p>Path Pattern: {match.path}</p> 15 <p>Matched URL: {match.url}</p> 16 <p>Exact Match: {match.isExact.toString()}</p> 17 </div> 18 ); 19}
The useRouteMatch hook can be particularly helpful when working with nested routes or when you need to construct links relative to the current route path.
To fully understand useRouteMatch, we need to explore how React Router handles path matching. React Router DOM compares the current URL against defined route paths and determines which components to render based on these matches.
The matching process follows these steps:
React Router examines the current URL path
It compares this path against all defined route paths
It identifies matches and extracts any URL parameters
It renders the corresponding route components
It provides match information to components via hooks or props
The useRouteMatch hook can be called in two different ways:
When called without arguments, useRouteMatch returns the match object for the current route component:
1const match = useRouteMatch();
This approach is useful when you need to access the match information for the route in which your component is rendered.
You can also provide a path pattern as an argument to check if the current URL matches that pattern:
1const matchProfile = useRouteMatch('/users/:userId/profile');
In this case, the hook returns either a match object if the pattern matches the current URL, or null if it doesn't match. This makes it valuable for conditional rendering based on the URL path.
Let's look at some practical examples of how to use the useRouteMatch hook in real applications.
1import React from 'react'; 2import { useRouteMatch, Route, Link } from 'react-router-dom'; 3 4function Dashboard() { 5 // Check if the current URL matches the settings path 6 const settingsMatch = useRouteMatch('/dashboard/settings'); 7 8 return ( 9 <div> 10 <h1>Dashboard</h1> 11 12 <nav> 13 <ul> 14 <li> 15 <Link to="/dashboard/profile">Profile</Link> 16 </li> 17 <li> 18 <Link to="/dashboard/settings">Settings</Link> 19 </li> 20 </ul> 21 </nav> 22 23 {/* Show a special notification only on the settings page */} 24 {settingsMatch && ( 25 <div className="notification"> 26 Settings are under maintenance 27 </div> 28 )} 29 30 <Route path="/dashboard/profile"> 31 <Profile /> 32 </Route> 33 34 <Route path="/dashboard/settings"> 35 <Settings /> 36 </Route> 37 </div> 38 ); 39}
The useRouteMatch hook helps create relative links based on the current route path:
1import React from 'react'; 2import { useRouteMatch, Link, Route, Switch } from 'react-router-dom'; 3 4function UserSection() { 5 // Get match information for the current route 6 const match = useRouteMatch(); 7 8 return ( 9 <div> 10 <h2>User Section</h2> 11 12 <nav> 13 <ul> 14 {/* Create links relative to the current URL */} 15 <li><Link to={`${match.url}/profile`}>Profile</Link></li> 16 <li><Link to={`${match.url}/settings`}>Settings</Link></li> 17 <li><Link to={`${match.url}/notifications`}>Notifications</Link></li> 18 </ul> 19 </nav> 20 21 <Switch> 22 <Route path={`${match.path}/profile`}> 23 <UserProfile /> 24 </Route> 25 <Route path={`${match.path}/settings`}> 26 <UserSettings /> 27 </Route> 28 <Route path={`${match.path}/notifications`}> 29 <UserNotifications /> 30 </Route> 31 </Switch> 32 </div> 33 ); 34} 35 36export default function App() { 37 return ( 38 <div> 39 <nav> 40 <ul> 41 <li><Link to="/users">Users</Link></li> 42 <li><Link to="/about">About</Link></li> 43 </ul> 44 </nav> 45 46 <Switch> 47 <Route path="/users"> 48 <UserSection /> 49 </Route> 50 <Route path="/about"> 51 <About /> 52 </Route> 53 </Switch> 54 </div> 55 ); 56}
One of the most powerful features of useRouteMatch is its ability to extract URL parameters from dynamic segments in the route path. When you define a route with parameters (like /users/:userId
), the match object's params property contains these values.
1import React from 'react'; 2import { useRouteMatch } from 'react-router-dom'; 3 4function UserDetail() { 5 // Match against a path with a parameter 6 const match = useRouteMatch('/users/:userId'); 7 8 if (!match) { 9 return <div>No match found</div>; 10 } 11 12 // Access the userId parameter 13 const { userId } = match.params; 14 15 return ( 16 <div> 17 <h2>User Details for ID: {userId}</h2> 18 {/* Rest of your component */} 19 </div> 20 ); 21}
This approach differs from using the useParams hook directly, as useRouteMatch gives you both the parameters and additional match information.
The match object returned by useRouteMatch has both path and url properties, which can sometimes confuse:
• path - Represents the route path pattern used for matching
• url - Represents the matched portion of the URL path
Consider this example to understand the difference:
1// If your route is defined as: 2<Route path="/users/:userId/posts/:postId"> 3 <UserPost /> 4</Route> 5 6// And the current URL is: 7// /users/123/posts/456 8 9// Inside UserPost component: 10const match = useRouteMatch(); 11 12console.log(match.path); // Output: "/users/:userId/posts/:postId" 13console.log(match.url); // Output: "/users/123/posts/456"
The path contains the pattern with parameter placeholders, while the url contains the actual values in the current URL.
React Router offers several hooks for accessing routing information. Let's compare useRouteMatch with some of the other React Router hooks:
The useParams hook only returns the URL parameters object, while useRouteMatch provides a complete match object:
1// Using useParams 2const { userId } = useParams(); 3console.log(userId); // "123" 4 5// Using useRouteMatch 6const match = useRouteMatch(); 7console.log(match.params.userId); // "123" 8console.log(match.path); // "/users/:userId" 9console.log(match.url); // "/users/123"
The useLocation hook returns the current location object containing information about the entire URL, including the URL query string and URL hash fragment:
1// Using useLocation 2const location = useLocation(); 3console.log(location.pathname); // "/users/123" 4console.log(location.search); // "?tab=profile" 5console.log(location.hash); // "#summary" 6 7// Using useRouteMatch 8const match = useRouteMatch(); 9console.log(match.url); // "/users/123" 10// Note: useRouteMatch doesn't provide search or hash information
The useHistory hook from React Router gives you access to the history object that lets you manage and navigate the history stack:
1// Using useHistory 2const history = useHistory(); 3history.push('/dashboard'); 4 5// useRouteMatch doesn't provide navigation methods, only matching information 6const match = useRouteMatch();
The useRouteMatch hook accepts an optional second argument that allows you to customize how the path matching works:
1const match = useRouteMatch({ 2 path: '/users/:userId', 3 strict: true, 4 sensitive: true 5});
The options include:
• path - The path pattern to match against
• exact - When true, the pattern must match the entire URL path
• strict - When true, trailing slashes are considered during matching
• sensitive - When true, case-sensitive path matching is used
useRouteMatch is particularly useful with nested routes . It helps maintain the relationship between parent and child routes:
1import React from 'react'; 2import { useRouteMatch, Route, Switch, Link } from 'react-router-dom'; 3 4function ProductsSection() { 5 const match = useRouteMatch(); 6 7 return ( 8 <div> 9 <h2>Products</h2> 10 11 <ul> 12 <li> 13 <Link to={`${match.url}/electronics`}>Electronics</Link> 14 </li> 15 <li> 16 <Link to={`${match.url}/books`}>Books</Link> 17 </li> 18 </ul> 19 20 <Switch> 21 <Route path={`${match.path}/electronics`}> 22 <Electronics /> 23 </Route> 24 <Route path={`${match.path}/books`}> 25 <Books /> 26 </Route> 27 <Route exact path={match.path}> 28 <h3>Please select a category</h3> 29 </Route> 30 </Switch> 31 </div> 32 ); 33} 34 35function Electronics() { 36 const match = useRouteMatch(); 37 38 return ( 39 <div> 40 <h3>Electronics</h3> 41 42 <ul> 43 <li> 44 <Link to={`${match.url}/phones`}>Phones</Link> 45 </li> 46 <li> 47 <Link to={`${match.url}/laptops`}>Laptops</Link> 48 </li> 49 </ul> 50 51 <Switch> 52 <Route path={`${match.path}/phones`}> 53 <h4>Phones</h4> 54 </Route> 55 <Route path={`${match.path}/laptops`}> 56 <h4>Laptops</h4> 57 </Route> 58 <Route exact path={match.path}> 59 <h4>Please select a product</h4> 60 </Route> 61 </Switch> 62 </div> 63 ); 64}
To fully understand useRouteMatch, it's helpful to know how it relates to the broader React Router context.
The location object represents the current URL in your application. React Router DOM provides this object to components through the useLocation hook or via the location prop. The location object contains:
• pathname - The path portion of the URL
• search - The URL query string
• hash - The URL hash fragment
• state - Location-specific state that was provided to this location
The useRouteMatch hook uses the current location to determine if there's a match against the provided path pattern.
React Router DOM uses a history object to manage the session history of your application. This object maintains a history stack and a pointer in the history stack that indicates the current entry.
When you navigate using methods like history.push()
, it pushes a new entry onto the history stack. The history object provides methods like:
• push(path)
- Pushes a new entry onto the history stack
• replace(path)
- Replaces the current entry in the history stack
• goBack()
- Navigates to the previous entry in the history stack
• goForward()
- Navigates to the next entry in the history stack
React Router supports different types of history implementations, including browser and memory history.
The useRouteMatch hook is particularly useful in the following scenarios:
When you need to create nested routes and want to maintain the relationship between parent and child routes
When you want to conditionally render components based on the current URL
When you need to extract and use URL parameters
When you need to create links relative to the current route
When you want to check if the current URL matches a specific pattern
To make the most of the useRouteMatch hook in your React Router applications, follow these best practices:
When defining nested routes, use the match.path for the Route component's path prop and match.url for creating Links:
1const match = useRouteMatch(); 2 3// For Route definitions, use match.path 4<Route path={`${match.path}/settings`}> 5 <Settings /> 6</Route> 7 8// For creating links, use match.url 9<Link to={`${match.url}/settings`}>Settings</Link>
This ensures your routes work correctly with URL parameters.
For more complex routing needs, combine useRouteMatch with other React Router hooks:
1import { useRouteMatch, useParams, useLocation, useHistory } from 'react-router-dom'; 2 3function AdvancedComponent() { 4 const match = useRouteMatch(); 5 const params = useParams(); 6 const location = useLocation(); 7 const history = useHistory(); 8 9 // Now you have access to all routing aspects 10}
The useRouteMatch hook performs pattern matching on every render. For complex applications with deep component trees, consider whether you need the match information at each level.
While the component prop approach is less common in modern React Router applications, it can be used with useRouteMatch:
1import React from 'react'; 2import { Route, useRouteMatch } from 'react-router-dom'; 3 4function UserSection() { 5 const match = useRouteMatch(); 6 7 return ( 8 <div> 9 <h2>User Section</h2> 10 11 <Route 12 path={`${match.path}/profile`} 13 component={UserProfile} 14 /> 15 16 <Route 17 path={`${match.path}/settings`} 18 render={props => <UserSettings {...props} additionalProp="value" />} 19 /> 20 </div> 21 ); 22}
The useRouteMatch hook can be used with route children to create more flexible routing structures:
1import React from 'react'; 2import { Route, useRouteMatch, Switch } from 'react-router-dom'; 3 4function Dashboard() { 5 const match = useRouteMatch(); 6 7 return ( 8 <div> 9 <h1>Dashboard</h1> 10 11 <Switch> 12 <Route path={`${match.path}/analytics`}> 13 {/* Route children approach */} 14 <Analytics /> 15 </Route> 16 </Switch> 17 </div> 18 ); 19}
The useRouteMatch hook focuses on path parameters, not query parameters. To work with query parameters, you'll need to combine it with the useLocation hook:
1import React from 'react'; 2import { useRouteMatch, useLocation } from 'react-router-dom'; 3 4function SearchResults() { 5 const match = useRouteMatch('/search'); 6 const location = useLocation(); 7 8 // Parse query parameters 9 const queryParams = new URLSearchParams(location.search); 10 const query = queryParams.get('q'); 11 const page = queryParams.get('page') || '1'; 12 13 if (!match) { 14 return <div>Not on the search page</div>; 15 } 16 17 return ( 18 <div> 19 <h2>Search Results for: {query}</h2> 20 <p>Page: {page}</p> 21 </div> 22 ); 23}
In single-page applications built with React Router, the useRouteMatch hook plays a crucial role in managing client-side routing. When the URL changes in a single-page application, React Router updates its internal state without requiring a full page reload.
The useRouteMatch hook attempts to match the current URL against a provided pattern, allowing components to render based on the URL path. This enables a seamless user experience as users navigate through the application.
The useRouteMatch hook from React Router DOM is a powerful tool for working with routes in React applications. It provides a way to match the current URL against a path pattern and extract valuable information about the match.
Key takeaways about useRouteMatch:
It returns a match object containing path, url, isExact, and params properties
It can be used with or without arguments to match against the current URL
It helps create nested routes and relative links
It works well with other React Router hooks like useParams, useLocation, and useHistory
By understanding useRouteMatch and incorporating it into your React Router applications, you can create more flexible and maintainable routing structures that enhance the user experience.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.