The useRouteMatch hook provides access to the current route's matching information without actually rendering a <Route> component. It's primarily used for:
Accessing current route parameters
Checking if a path matches the current URL
Building nested routes programmatically
Basic Usage
1. Accessing Current Match Information
import { useRouteMatch } from 'react-router-dom';
function UserProfile() {
const match = useRouteMatch();
// Returns:
// {
// path: '/users/:id',
// url: '/users/123',
// params: { id: '123' },
// isExact: true
// }
return <div>User ID: {match.params.id}</div>;
}
2. Checking Path Matches
function Navigation() {
const isUsersPage = useRouteMatch('/users');
return (
<nav className={isUsersPage ? 'active' : ''}>
Users Section
</nav>
);
}
3. Nested Route Construction
function Dashboard() {
const { path, url } = useRouteMatch();
return (
<div>
<Link to={`${url}/settings`}>Settings</Link>
<Switch>
<Route exact path={path}>
<Home />
</Route>
<Route path={`${path}/settings`}>
<Settings />
</Route>
</Switch>
</div>
);
}