router-query/repository-context/docs/router/api/router/useMatchHook.md
Version 663282b0ebbc.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.
← Return to resource and package checksum
id: useMatchHook title: useMatch hook
The useMatch hook returns a RouteMatch in the component tree. The raw route match contains all of the information about a route match in the router and also powers many other hooks under the hood like useParams, useLoaderData, useRouteContext, and useSearch.
useMatch options
The useMatch hook accepts a single argument, an options object.
opts.from option
- Type:
string - The route id of a match
- Optional, but recommended for full type safety.
- If
opts.strictistrue,fromis required and TypeScript will warn for this option if it is not provided. - If
opts.strictisfalse,frommust not be set and TypeScript will provided loosened types for the returnedRouteMatch.
opts.strict option
- Type:
boolean - Optional
default: true- If
false, theopts.frommust not be set and types will be loosened toPartial<RouteMatch>to reflect the shared types of all matches.
opts.select option
- Optional
(match: RouteMatch) => TSelected- If supplied, this function will be called with the route match and the return value will be returned from
useMatch. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
opts.structuralSharing option
- Type:
boolean - Optional
- Configures whether structural sharing is enabled for the value returned by
select. - See the Render Optimizations guide for more information.
opts.shouldThrow option
- Type:
boolean - Optional
default: true- If
false,useMatchwill not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will returnundefined.
useMatch returns
- If a
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theRouteMatchobject or a loosened version of theRouteMatchobject ifopts.strictisfalse.
Examples
Accessing a route match
import { useMatch } from '@tanstack/react-router'
function Component() {
const match = useMatch({ from: '/posts/$postId' })
// ^? strict match for RouteMatch
// ...
}
Accessing the root route's match
import {
useMatch,
rootRouteId, // <<<< use this token!
} from '@tanstack/react-router'
function Component() {
const match = useMatch({ from: rootRouteId })
// ^? strict match for RouteMatch
// ...
}
Checking if a specific route is currently rendered
import { useMatch } from '@tanstack/react-router'
function Component() {
const match = useMatch({ from: '/posts', shouldThrow: false })
// ^? RouteMatch | undefined
if (match !== undefined) {
// ...
}
}