Skip to content

Free MIT template · Day 6 of 365

You're looking at a demo. Download the built static files (drop on any host) or grab the full source to customize.

↓ Download static ↓ Source (Astro) All 365 →Hire me →

# useRoute()

`useRoute()` reads the current match from a `<Router />` ancestor. It’s the React adapter’s primary read API.

## Import

    import { useRoute } from 'routekit/react';

## Signature

    function useRoute<T extends RouteDefinition[]>(): UseRouteResult<T> | null;
    type UseRouteResult<T> = {  match: Match<T>;  Page: ComponentType<{ params: Record<string, string> }> | null;  isLoading: boolean;};

## Return

Field | Type | Description
--- | --- | ---
`match` | `Match<T>` | Same shape returned by `router.match()`. Has `path`, `url`, `params`, `meta`.
`Page` | `Component | null`
`isLoading` | `boolean` | `true` between navigation start and chunk resolution.

The hook returns `null` if called outside a `<Router />` ancestor — fail-loud, not silent.

## Example

    import { useRoute } from 'routekit/react';
    function Outlet() {  const route = useRoute();  if (!route) return null;  if (route.isLoading) return <Spinner />;  if (!route.Page) return <NotFound />;
      return <route.Page params={route.match.params} />;}

## Type-safe params

When you pass `routes` to `<Router />` with `as const`, `match.params` narrows by `match.path`:

    function PostPage() {  const route = useRoute<typeof routes>();  if (!route || route.match.path !== '/posts/:id') return null;  // ↓ params is now typed: { id: string }  return <article>Post {route.match.params.id}</article>;}

The pattern is verbose but explicit — the alternative (overloading the hook by route name) was rejected because it requires a build step.

## When to use

- Inside any component that needs to know the current URL or params.
- Inside a `<Link>` wrapper that toggles active styling.
- Inside an analytics layer that listens for route changes.

## When NOT to use

- Outside a `<Router />`. Returns `null`. Caller must handle.
- For navigation. Use `router.go()` or programmatic navigation — there’s no `navigate()` returned from this hook by design. Routes are owned by `<Router />`, not by render-tree state.

Don't subscribe per-component

Every call to `useRoute()` subscribes a component to route changes. In a tree with hundreds of links, this is fine — each subscription is a single Context read. In a list rendering 10,000 rows, lift the route lookup to a parent and pass it down.