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

useRouterState.tsx

77 lines2.6 KB

1'use client'
2​
3import { useSelector } from '@tanstack/react-store'
4import { isServer } from '@tanstack/router-core/isServer'
5import { useRouter } from './useRouter'
6import { useStructuralSharing } from './useMatch'
7import type {
8 AnyRouter,
9 RegisteredRouter,
10 RouterState,
11} from '@tanstack/router-core'
12import type {
13 StructuralSharingOption,
14 ValidateSelected,
15} from './structuralSharing'
16​
17export type UseRouterStateOptions<
18 TRouter extends AnyRouter,
19 TSelected,
20 TStructuralSharing,
21> = {
22 router?: TRouter
23 select?: (
24 state: RouterState<TRouter['routeTree']>,
25 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
26} & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>
27​
28export type UseRouterStateResult<
29 TRouter extends AnyRouter,
30 TSelected,
31> = unknown extends TSelected ? RouterState<TRouter['routeTree']> : TSelected
32​
33/**
34 * Subscribe to the router's state store with optional selection and
35 * structural sharing for render optimization.
36 *
37 * Options:
38 * - `select`: Project the full router state to a derived slice
39 * - `structuralSharing`: Replace-equal semantics for stable references
40 * - `router`: Read state from a specific router instance instead of context
41 *
42 * @returns The selected router state (or the full state by default).
43 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useRouterStateHook
44 */
45export function useRouterState<
46 TRouter extends AnyRouter = RegisteredRouter,
47 TSelected = unknown,
48 TStructuralSharing extends boolean = boolean,
49>(
50 opts?: UseRouterStateOptions<TRouter, TSelected, TStructuralSharing>,
51): UseRouterStateResult<TRouter, TSelected> {
52 const contextRouter = useRouter<TRouter>({
53 warn: opts?.router === undefined,
54 })
55 const router = opts?.router || contextRouter
56​
57 // During SSR we render exactly once and do not need reactivity.
58 // Avoid subscribing to the store (and any structural sharing work) on the server.
59 // The expression must stay inlined in the `if` so bundlers fold the
60 // browser-build constant `isServer = false` and drop this server block.
61 if (isServer ?? router.isServer) {
62 const state = router.stores.__store.get() as RouterState<
63 TRouter['routeTree']
64 >
65 return (opts?.select ? opts.select(state) : state) as UseRouterStateResult<
66 TRouter,
67 TSelected
68 >
69 }
70​
71 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
72 return useSelector(
73 router.stores.__store,
74 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
75 useStructuralSharing(opts, router),
76 ) as UseRouterStateResult<TRouter, TSelected>