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

useLocation.tsx

68 lines2.1 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 StructuralSharingOption,
9 ValidateSelected,
10} from './structuralSharing'
11import type {
12 AnyRouter,
13 RegisteredRouter,
14 RouterState,
15} from '@tanstack/router-core'
16​
17export interface UseLocationBaseOptions<
18 TRouter extends AnyRouter,
19 TSelected,
20 TStructuralSharing extends boolean = boolean,
21> {
22 select?: (
23 state: RouterState<TRouter['routeTree']>['location'],
24 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
26​
27export type UseLocationResult<
28 TRouter extends AnyRouter,
29 TSelected,
30> = unknown extends TSelected
31 ? RouterState<TRouter['routeTree']>['location']
32 : TSelected
33​
34/**
35 * Read the current location from the router state with optional selection.
36 * Useful for subscribing to just the pieces of location you care about.
37 *
38 * Options:
39 * - `select`: Project the `location` object to a derived value
40 * - `structuralSharing`: Enable structural sharing for stable references
41 *
42 * @returns The current location (or selected value).
43 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLocationHook
44 */
45export function useLocation<
46 TRouter extends AnyRouter = RegisteredRouter,
47 TSelected = unknown,
48 TStructuralSharing extends boolean = boolean,
49>(
50 opts?: UseLocationBaseOptions<TRouter, TSelected, TStructuralSharing> &
51 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
52): UseLocationResult<TRouter, TSelected> {
53 const router = useRouter<TRouter>()
54​
55 if (isServer ?? router.isServer) {
56 const location = router.stores.location.get()
57 return (
58 opts?.select ? opts.select(location as any) : location
59 ) as UseLocationResult<TRouter, TSelected>
60 }
61​
62 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
63 return useSelector(
64 router.stores.location,
65 // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
66 useStructuralSharing(opts, router),
67 ) as UseLocationResult<TRouter, TSelected>