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

useRouter.tsx

35 lines1.1 KB

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 (!value) {
22 warnMissingRouter(opts)
23 }
24 return value as any
26​
27// Kept out of the hook body: this dev-only branch runs for every Link and
28// route hook, and on the server each `process.env` read is a native call.
29function warnMissingRouter(opts?: { warn?: boolean }) {
30 if (process.env.NODE_ENV !== 'production' && (opts?.warn ?? true)) {
31 console.warn(
32 'Warning: useRouter must be used inside a <RouterProvider> component!',
33 )
34 }