Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useRouter.tsx

29 lines902 Bytes

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