> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/TanStack/router/llms.txt
> Use this file to discover all available pages before exploring further.

# Hooks

TanStack Router provides a comprehensive set of hooks for accessing router state, navigation, and route information with full type safety.

## Router Hooks

### `useRouter`

Access the current TanStack Router instance from React context.

```tsx theme={null}
import { useRouter } from '@tanstack/react-router'

function MyComponent() {
  const router = useRouter()
  
  return <div>Current path: {router.state.location.pathname}</div>
}
```

**Source:** `packages/react-router/src/useRouter.tsx:16-25`

<ParamField path="opts" type="{ warn?: boolean }">
  <Expandable title="Options">
    <ParamField path="warn" type="boolean" default="true">
      Log a warning if no router context is found.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="TRouter">
  The registered router instance.
</ResponseField>

### `useRouterState`

Subscribe to the router's state store with optional selection and structural sharing.

```tsx theme={null}
import { useRouterState } from '@tanstack/react-router'

function MyComponent() {
  const isLoading = useRouterState({ 
    select: (state) => state.isLoading 
  })
  
  return isLoading ? <Spinner /> : <Content />
}
```

**Source:** `packages/react-router/src/useRouterState.tsx:44-86`

<ParamField path="opts" type="UseRouterStateOptions">
  <Expandable title="Options">
    <ParamField path="select" type="(state: RouterState) => TSelected">
      Project the full router state to a derived slice for render optimization.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing for stable references (replace-equal semantics).
    </ParamField>

    <ParamField path="router" type="TRouter">
      Read state from a specific router instance instead of context.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="TSelected | RouterState">
  The selected router state (or the full state by default).
</ResponseField>

## Navigation Hooks

### `useNavigate`

Imperative navigation hook that returns a stable navigate function.

```tsx theme={null}
import { useNavigate } from '@tanstack/react-router'

function MyComponent() {
  const navigate = useNavigate()
  
  const handleClick = () => {
    navigate({ to: '/posts/$postId', params: { postId: '123' } })
  }
  
  return <button onClick={handleClick}>Go to Post</button>
}
```

**Source:** `packages/react-router/src/useNavigate.tsx:26-43`

<ParamField path="defaultOpts" type="{ from?: string }">
  <Expandable title="Options">
    <ParamField path="from" type="string">
      Optional route base used to resolve relative `to` paths.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="(options: NavigateOptions) => Promise<void>">
  A function that accepts NavigateOptions including:

  * `to` - Destination path
  * `params` - Path parameters
  * `search` - Search parameters
  * `hash` - URL hash
  * `replace` - Replace history entry
  * `resetScroll` - Reset scroll position
</ResponseField>

### `useLocation`

Read the current location from the router state.

```tsx theme={null}
import { useLocation } from '@tanstack/react-router'

function MyComponent() {
  const location = useLocation()
  
  return <div>Current path: {location.pathname}</div>
}
```

**Source:** `packages/react-router/src/useLocation.tsx:40-52`

<ParamField path="opts" type="UseLocationOptions">
  <Expandable title="Options">
    <ParamField path="select" type="(location: Location) => TSelected">
      Project the location object to a derived value.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing for stable references.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="Location | TSelected">
  The current location object with properties:

  * `pathname` - Current path
  * `search` - Parsed search params
  * `hash` - URL hash
  * `href` - Full URL
  * `state` - Location state
</ResponseField>

## Route Data Hooks

### `useParams`

Access the current route's path parameters with type safety.

```tsx theme={null}
import { useParams } from '@tanstack/react-router'

function PostComponent() {
  const { postId } = useParams({ from: '/posts/$postId' })
  
  return <div>Post ID: {postId}</div>
}
```

**Source:** `packages/react-router/src/useParams.tsx:76-107`

<ParamField path="opts" type="UseParamsOptions" required>
  <Expandable title="Options">
    <ParamField path="from" type="string">
      The route ID to get params from.
    </ParamField>

    <ParamField path="strict" type="boolean" default="true">
      Whether to enforce strict typing.
    </ParamField>

    <ParamField path="select" type="(params: TParams) => TSelected">
      Project the params object to a derived value.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing for stable references.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="TParams | TSelected">
  The params object (or selected value) for the matched route.
</ResponseField>

### `useSearch`

Read and select the current route's search parameters with type safety.

```tsx theme={null}
import { useSearch } from '@tanstack/react-router'

function PostsComponent() {
  const search = useSearch({ from: '/posts' })
  
  return <div>Page: {search.page}</div>
}
```

**Source:** `packages/react-router/src/useSearch.tsx:76-105`

<ParamField path="opts" type="UseSearchOptions" required>
  <Expandable title="Options">
    <ParamField path="from" type="string">
      The route ID to get search params from.
    </ParamField>

    <ParamField path="strict" type="boolean" default="true">
      Control how strictly search is typed.
    </ParamField>

    <ParamField path="select" type="(search: TSearch) => TSelected">
      Map the search object to a derived value.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing for stable references.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="TSearch | TSelected">
  The search object (or selected value) for the matched route.
</ResponseField>

### `useLoaderData`

Read and select the current route's loader data with type safety.

```tsx theme={null}
import { useLoaderData } from '@tanstack/react-router'

function PostComponent() {
  const { post } = useLoaderData({ from: '/posts/$postId' })
  
  return <h1>{post.title}</h1>
}
```

**Source:** `packages/react-router/src/useLoaderData.tsx:68-91`

<ParamField path="opts" type="UseLoaderDataOptions" required>
  <Expandable title="Options">
    <ParamField path="from" type="string">
      The route ID to get loader data from.
    </ParamField>

    <ParamField path="strict" type="boolean" default="true">
      Choose strictness of typing.
    </ParamField>

    <ParamField path="select" type="(data: TLoaderData) => TSelected">
      Map the loader data to a derived value.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing for stable references.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="TLoaderData | TSelected">
  The loader data (or selected value) for the matched route.
</ResponseField>

## Match Hooks

### `useMatch`

Read and select the nearest or targeted route match.

```tsx theme={null}
import { useMatch } from '@tanstack/react-router'

function MyComponent() {
  const match = useMatch({ from: '/posts/$postId' })
  
  return <div>Match ID: {match.id}</div>
}
```

**Source:** `packages/react-router/src/useMatch.tsx:82-123`

<ParamField path="opts" type="UseMatchOptions" required>
  <Expandable title="Options">
    <ParamField path="from" type="string">
      The route ID to match.
    </ParamField>

    <ParamField path="strict" type="boolean" default="true">
      Whether to enforce strict typing.
    </ParamField>

    <ParamField path="select" type="(match: RouteMatch) => TSelected">
      Project the match to a derived value.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="RouteMatch | TSelected">
  The route match object containing:

  * `id` - Match ID
  * `routeId` - Route ID
  * `pathname` - Matched pathname
  * `params` - Path parameters
  * `search` - Search parameters
  * `loaderData` - Loader data
  * `context` - Route context
</ResponseField>

### `useMatches`

Read the full array of active route matches or select a derived subset.

```tsx theme={null}
import { useMatches } from '@tanstack/react-router'

function Breadcrumbs() {
  const matches = useMatches()
  
  return (
    <nav>
      {matches.map(match => (
        <span key={match.id}>{match.routeId}</span>
      ))}
    </nav>
  )
}
```

**Source:** `packages/react-router/src/Matches.tsx:233-250`

<ParamField path="opts" type="UseMatchesOptions">
  <Expandable title="Options">
    <ParamField path="select" type="(matches: RouteMatch[]) => TSelected">
      Project the matches array to a derived value.
    </ParamField>

    <ParamField path="structuralSharing" type="boolean">
      Enable structural sharing.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="RouteMatch[] | TSelected">
  The array of matches (or the selected value).
</ResponseField>

### `useMatchRoute`

Create a matcher function for testing locations against route definitions.

```tsx theme={null}
import { useMatchRoute } from '@tanstack/react-router'

function MyComponent() {
  const matchRoute = useMatchRoute()
  const isPostsPage = matchRoute({ to: '/posts' })
  
  return isPostsPage ? <PostsHeader /> : <DefaultHeader />
}
```

**Source:** `packages/react-router/src/Matches.tsx:144-174`

<ResponseField name="returns" type="(options: MatchRouteOptions) => false | TParams">
  A matchRoute function that returns `false` (no match) or the matched params object. Options include:

  * `to` - Route to match
  * `params` - Match specific params
  * `search` - Match specific search
  * `fuzzy` - Allow fuzzy matching
  * `pending` - Match against pending location
  * `caseSensitive` - Case-sensitive matching
</ResponseField>

## Blocker Hook

### `useBlocker`

Block navigation with custom logic and optional user confirmation.

```tsx theme={null}
import { useBlocker } from '@tanstack/react-router'

function FormComponent() {
  const [isDirty, setIsDirty] = useState(false)
  
  useBlocker({
    shouldBlockFn: () => isDirty,
    enableBeforeUnload: true,
    withResolver: true,
  })
  
  return <form>...</form>
}
```

**Source:** `packages/react-router/src/useBlocker.tsx:131-260`

<ParamField path="opts" type="UseBlockerOpts" required>
  <Expandable title="Options">
    <ParamField path="shouldBlockFn" type="(args: BlockerArgs) => boolean | Promise<boolean>" required>
      Function to determine if navigation should be blocked. Receives current and next locations.
    </ParamField>

    <ParamField path="enableBeforeUnload" type="boolean | (() => boolean)" default="true">
      Enable browser's beforeunload warning.
    </ParamField>

    <ParamField path="disabled" type="boolean" default="false">
      Disable the blocker.
    </ParamField>

    <ParamField path="withResolver" type="boolean" default="false">
      Return a resolver object with proceed/reset functions.
    </ParamField>
  </Expandable>
</ParamField>

<ResponseField name="returns" type="void | BlockerResolver">
  When `withResolver: true`, returns:

  * `status` - 'idle' | 'blocked'
  * `current` - Current location info
  * `next` - Next location info
  * `action` - History action
  * `proceed()` - Allow navigation
  * `reset()` - Cancel navigation
</ResponseField>

## Usage Examples

### Router State Selection

```tsx theme={null}
function NavigationIndicator() {
  const { isLoading, location } = useRouterState({
    select: (state) => ({
      isLoading: state.isLoading,
      location: state.location.pathname,
    }),
  })
  
  return isLoading ? <ProgressBar /> : null
}
```

### Imperative Navigation

```tsx theme={null}
function LoginButton() {
  const navigate = useNavigate()
  
  const handleLogin = async () => {
    await loginUser()
    navigate({ 
      to: '/dashboard',
      replace: true,
    })
  }
  
  return <button onClick={handleLogin}>Login</button>
}
```

### Type-Safe Params

```tsx theme={null}
function PostPage() {
  const { postId, commentId } = useParams({ 
    from: '/posts/$postId/comments/$commentId',
    select: (params) => ({
      postId: params.postId,
      commentId: params.commentId,
    }),
  })
  
  return <Comment postId={postId} commentId={commentId} />
}
```

### Search Params with Selection

```tsx theme={null}
function ProductList() {
  const page = useSearch({
    from: '/products',
    select: (search) => search.page ?? 1,
  })
  
  const products = useProducts(page)
  
  return <ProductGrid products={products} />
}
```

### Loader Data Access

```tsx theme={null}
function UserProfile() {
  const user = useLoaderData({
    from: '/users/$userId',
    select: (data) => data.user,
  })
  
  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  )
}
```

### Conditional Rendering with Match

```tsx theme={null}
function Navigation() {
  const matchRoute = useMatchRoute()
  
  const isSettings = matchRoute({ to: '/settings', fuzzy: true })
  const isAdmin = matchRoute({ to: '/admin' })
  
  return (
    <nav>
      <Link to="/">Home</Link>
      {isSettings && <SettingsNav />}
      {isAdmin && <AdminNav />}
    </nav>
  )
}
```

### Breadcrumbs with Matches

```tsx theme={null}
function Breadcrumbs() {
  const matches = useMatches({
    select: (matches) => matches.map(match => ({
      id: match.id,
      pathname: match.pathname,
      // Access custom metadata from route
      title: match.context?.breadcrumb,
    })),
  })
  
  return (
    <nav>
      {matches.map((match, i) => (
        <span key={match.id}>
          {i > 0 && ' > '}
          <Link to={match.pathname}>{match.title}</Link>
        </span>
      ))}
    </nav>
  )
}
```

### Navigation Blocker

```tsx theme={null}
function EditForm() {
  const [formData, setFormData] = useState(initialData)
  const [originalData] = useState(initialData)
  
  const hasChanges = !deepEqual(formData, originalData)
  
  const blocker = useBlocker({
    shouldBlockFn: ({ current, next }) => {
      return hasChanges && current.routeId !== next.routeId
    },
    withResolver: true,
  })
  
  return (
    <>
      <form>
        <input 
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
        />
      </form>
      
      {blocker.status === 'blocked' && (
        <Dialog>
          <p>You have unsaved changes. Are you sure you want to leave?</p>
          <button onClick={blocker.proceed}>Leave</button>
          <button onClick={blocker.reset}>Stay</button>
        </Dialog>
      )}
    </>
  )
}
```

### Location Tracking

```tsx theme={null}
function Analytics() {
  const pathname = useLocation({ 
    select: (loc) => loc.pathname 
  })
  
  useEffect(() => {
    trackPageView(pathname)
  }, [pathname])
  
  return null
}
```

## Performance Tips

### Use Selectors

Always use the `select` option to narrow down your subscription:

```tsx theme={null}
// ❌ Re-renders on any router state change
const state = useRouterState()

// ✅ Only re-renders when isLoading changes
const isLoading = useRouterState({ 
  select: (s) => s.isLoading 
})
```

### Enable Structural Sharing

For complex selections, enable structural sharing:

```tsx theme={null}
const metadata = useMatches({
  select: (matches) => matches.map(m => m.context?.metadata),
  structuralSharing: true, // Prevents unnecessary re-renders
})
```

### Memoize Selectors

For expensive selections, memoize the selector:

```tsx theme={null}
const selector = useCallback(
  (state) => computeExpensiveValue(state),
  [dependencies]
)

const value = useRouterState({ select: selector })
```

## See Also

* [Router Guide](../../guide/router-context)
* [Data Loading Guide](../../guide/data-loading)
* [Navigation Guide](../../guide/navigation)
