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

useRouterState.tsx

76 lines2.5 KB

1import { useStore } from '@tanstack/react-store'
2import { useRef } from 'react'
3import { replaceEqualDeep } from '@tanstack/router-core'
4import { useRouter } from './useRouter'
5import type {
6 AnyRouter,
7 RegisteredRouter,
8 RouterState,
9} from '@tanstack/router-core'
10import type {
11 StructuralSharingOption,
12 ValidateSelected,
13} from './structuralSharing'
14​
15export type UseRouterStateOptions<
16 TRouter extends AnyRouter,
17 TSelected,
18 TStructuralSharing,
19> = {
20 router?: TRouter
21 select?: (
22 state: RouterState<TRouter['routeTree']>,
23 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
24} & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>
25​
26export type UseRouterStateResult<
27 TRouter extends AnyRouter,
28 TSelected,
29> = unknown extends TSelected ? RouterState<TRouter['routeTree']> : TSelected
30​
31/**
32 * Subscribe to the router's state store with optional selection and
33 * structural sharing for render optimization.
34 *
35 * Options:
36 * - `select`: Project the full router state to a derived slice
37 * - `structuralSharing`: Replace-equal semantics for stable references
38 * - `router`: Read state from a specific router instance instead of context
39 *
40 * @returns The selected router state (or the full state by default).
41 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useRouterStateHook
42 */
43/**
44 * Subscribe to the router's state store with optional selection and
45 * structural sharing for render optimization.
46 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useRouterStateHook
47 */
48export function useRouterState<
49 TRouter extends AnyRouter = RegisteredRouter,
50 TSelected = unknown,
51 TStructuralSharing extends boolean = boolean,
52>(
53 opts?: UseRouterStateOptions<TRouter, TSelected, TStructuralSharing>,
54): UseRouterStateResult<TRouter, TSelected> {
55 const contextRouter = useRouter<TRouter>({
56 warn: opts?.router === undefined,
57 })
58 const router = opts?.router || contextRouter
59 const previousResult =
60 useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>(undefined)
61​
62 return useStore(router.__store, (state) => {
63 if (opts?.select) {
64 if (opts.structuralSharing ?? router.options.defaultStructuralSharing) {
65 const newSlice = replaceEqualDeep(
66 previousResult.current,
67 opts.select(state),
68 )
69 previousResult.current = newSlice
70 return newSlice
71 }
72 return opts.select(state)
73 }
74 return state
75 }) as UseRouterStateResult<TRouter, TSelected>