Open History to see the last commit
1import * as React from 'react'
2import warning from 'tiny-warning'
3import { getRouterContext } from './routerContext'
4import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core'
5β
6/**
7 * Access the current TanStack Router instance from React context.
8 * Must be used within a `RouterProvider`.
9 *
10 * Options:
11 * - `warn`: Log a warning if no router context is found (default: true).
12 *
13 * @returns The registered router instance.
14 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useRouterHook
15 */
16/**
17 * Access the current TanStack Router instance from React context.
18 * Must be used within a `RouterProvider`.
19 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useRouterHook
20 */
21export function useRouter<TRouter extends AnyRouter = RegisteredRouter>(opts?: {
22 warn?: boolean
23}): TRouter {
24 const value = React.useContext(getRouterContext())
25 warning(
26 !((opts?.warn ?? true) && !value),
27 'useRouter must be used inside a <RouterProvider> component!',
28 )
29 return value as any
30}