@tanstack/react-router 1.121.16 → 1.121.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/package.json +2 -2
  2. package/dist/cjs/Asset.cjs +0 -41
  3. package/dist/cjs/Asset.cjs.map +0 -1
  4. package/dist/cjs/Asset.d.cts +0 -2
  5. package/dist/cjs/CatchBoundary.cjs +0 -114
  6. package/dist/cjs/CatchBoundary.cjs.map +0 -1
  7. package/dist/cjs/CatchBoundary.d.cts +0 -12
  8. package/dist/cjs/ClientOnly.cjs +0 -20
  9. package/dist/cjs/ClientOnly.cjs.map +0 -1
  10. package/dist/cjs/ClientOnly.d.cts +0 -29
  11. package/dist/cjs/HeadContent.cjs +0 -155
  12. package/dist/cjs/HeadContent.cjs.map +0 -1
  13. package/dist/cjs/HeadContent.d.cts +0 -7
  14. package/dist/cjs/Match.cjs +0 -257
  15. package/dist/cjs/Match.cjs.map +0 -1
  16. package/dist/cjs/Match.d.cts +0 -8
  17. package/dist/cjs/Matches.cjs +0 -136
  18. package/dist/cjs/Matches.cjs.map +0 -1
  19. package/dist/cjs/Matches.d.cts +0 -26
  20. package/dist/cjs/RouterProvider.cjs +0 -33
  21. package/dist/cjs/RouterProvider.cjs.map +0 -1
  22. package/dist/cjs/RouterProvider.d.cts +0 -10
  23. package/dist/cjs/SafeFragment.cjs +0 -8
  24. package/dist/cjs/SafeFragment.cjs.map +0 -1
  25. package/dist/cjs/SafeFragment.d.cts +0 -1
  26. package/dist/cjs/ScriptOnce.cjs +0 -28
  27. package/dist/cjs/ScriptOnce.cjs.map +0 -1
  28. package/dist/cjs/ScriptOnce.d.cts +0 -5
  29. package/dist/cjs/Scripts.cjs +0 -51
  30. package/dist/cjs/Scripts.cjs.map +0 -1
  31. package/dist/cjs/Scripts.d.cts +0 -1
  32. package/dist/cjs/ScrollRestoration.cjs +0 -39
  33. package/dist/cjs/ScrollRestoration.cjs.map +0 -1
  34. package/dist/cjs/ScrollRestoration.d.cts +0 -14
  35. package/dist/cjs/Transitioner.cjs +0 -115
  36. package/dist/cjs/Transitioner.cjs.map +0 -1
  37. package/dist/cjs/Transitioner.d.cts +0 -1
  38. package/dist/cjs/awaited.cjs +0 -48
  39. package/dist/cjs/awaited.cjs.map +0 -1
  40. package/dist/cjs/awaited.d.cts +0 -10
  41. package/dist/cjs/fileRoute.cjs +0 -107
  42. package/dist/cjs/fileRoute.cjs.map +0 -1
  43. package/dist/cjs/fileRoute.d.cts +0 -54
  44. package/dist/cjs/history.d.cts +0 -8
  45. package/dist/cjs/index.cjs +0 -289
  46. package/dist/cjs/index.cjs.map +0 -1
  47. package/dist/cjs/index.d.cts +0 -55
  48. package/dist/cjs/lazyRouteComponent.cjs +0 -78
  49. package/dist/cjs/lazyRouteComponent.cjs.map +0 -1
  50. package/dist/cjs/lazyRouteComponent.d.cts +0 -2
  51. package/dist/cjs/link.cjs +0 -324
  52. package/dist/cjs/link.cjs.map +0 -1
  53. package/dist/cjs/link.d.cts +0 -48
  54. package/dist/cjs/matchContext.cjs +0 -27
  55. package/dist/cjs/matchContext.cjs.map +0 -1
  56. package/dist/cjs/matchContext.d.cts +0 -3
  57. package/dist/cjs/not-found.cjs +0 -40
  58. package/dist/cjs/not-found.cjs.map +0 -1
  59. package/dist/cjs/not-found.d.cts +0 -9
  60. package/dist/cjs/renderRouteNotFound.cjs +0 -22
  61. package/dist/cjs/renderRouteNotFound.cjs.map +0 -1
  62. package/dist/cjs/renderRouteNotFound.d.cts +0 -2
  63. package/dist/cjs/route.cjs +0 -205
  64. package/dist/cjs/route.cjs.map +0 -1
  65. package/dist/cjs/route.d.cts +0 -95
  66. package/dist/cjs/router.cjs +0 -22
  67. package/dist/cjs/router.cjs.map +0 -1
  68. package/dist/cjs/router.d.cts +0 -72
  69. package/dist/cjs/routerContext.cjs +0 -33
  70. package/dist/cjs/routerContext.cjs.map +0 -1
  71. package/dist/cjs/routerContext.d.cts +0 -8
  72. package/dist/cjs/scroll-restoration.cjs +0 -24
  73. package/dist/cjs/scroll-restoration.cjs.map +0 -1
  74. package/dist/cjs/scroll-restoration.d.cts +0 -1
  75. package/dist/cjs/serializer.d.cts +0 -6
  76. package/dist/cjs/structuralSharing.d.cts +0 -8
  77. package/dist/cjs/typePrimitives.d.cts +0 -16
  78. package/dist/cjs/useBlocker.cjs +0 -165
  79. package/dist/cjs/useBlocker.cjs.map +0 -1
  80. package/dist/cjs/useBlocker.d.cts +0 -66
  81. package/dist/cjs/useCanGoBack.cjs +0 -8
  82. package/dist/cjs/useCanGoBack.cjs.map +0 -1
  83. package/dist/cjs/useCanGoBack.d.cts +0 -1
  84. package/dist/cjs/useLoaderData.cjs +0 -15
  85. package/dist/cjs/useLoaderData.cjs.map +0 -1
  86. package/dist/cjs/useLoaderData.d.cts +0 -8
  87. package/dist/cjs/useLoaderDeps.cjs +0 -14
  88. package/dist/cjs/useLoaderDeps.cjs.map +0 -1
  89. package/dist/cjs/useLoaderDeps.d.cts +0 -8
  90. package/dist/cjs/useLocation.cjs +0 -10
  91. package/dist/cjs/useLocation.cjs.map +0 -1
  92. package/dist/cjs/useLocation.d.cts +0 -7
  93. package/dist/cjs/useMatch.cjs +0 -47
  94. package/dist/cjs/useMatch.cjs.map +0 -1
  95. package/dist/cjs/useMatch.d.cts +0 -10
  96. package/dist/cjs/useNavigate.cjs +0 -55
  97. package/dist/cjs/useNavigate.cjs.map +0 -1
  98. package/dist/cjs/useNavigate.d.cts +0 -5
  99. package/dist/cjs/useParams.cjs +0 -16
  100. package/dist/cjs/useParams.cjs.map +0 -1
  101. package/dist/cjs/useParams.d.cts +0 -9
  102. package/dist/cjs/useRouteContext.cjs +0 -11
  103. package/dist/cjs/useRouteContext.cjs.map +0 -1
  104. package/dist/cjs/useRouteContext.d.cts +0 -3
  105. package/dist/cjs/useRouter.cjs +0 -32
  106. package/dist/cjs/useRouter.cjs.map +0 -1
  107. package/dist/cjs/useRouter.d.cts +0 -4
  108. package/dist/cjs/useRouterState.cjs +0 -29
  109. package/dist/cjs/useRouterState.cjs.map +0 -1
  110. package/dist/cjs/useRouterState.d.cts +0 -8
  111. package/dist/cjs/useSearch.cjs +0 -16
  112. package/dist/cjs/useSearch.cjs.map +0 -1
  113. package/dist/cjs/useSearch.d.cts +0 -9
  114. package/dist/cjs/utils.cjs +0 -72
  115. package/dist/cjs/utils.cjs.map +0 -1
  116. package/dist/cjs/utils.d.cts +0 -49
  117. package/dist/esm/Asset.d.ts +0 -2
  118. package/dist/esm/Asset.js +0 -41
  119. package/dist/esm/Asset.js.map +0 -1
  120. package/dist/esm/CatchBoundary.d.ts +0 -12
  121. package/dist/esm/CatchBoundary.js +0 -97
  122. package/dist/esm/CatchBoundary.js.map +0 -1
  123. package/dist/esm/ClientOnly.d.ts +0 -29
  124. package/dist/esm/ClientOnly.js +0 -20
  125. package/dist/esm/ClientOnly.js.map +0 -1
  126. package/dist/esm/HeadContent.d.ts +0 -7
  127. package/dist/esm/HeadContent.js +0 -139
  128. package/dist/esm/HeadContent.js.map +0 -1
  129. package/dist/esm/Match.d.ts +0 -8
  130. package/dist/esm/Match.js +0 -240
  131. package/dist/esm/Match.js.map +0 -1
  132. package/dist/esm/Matches.d.ts +0 -26
  133. package/dist/esm/Matches.js +0 -119
  134. package/dist/esm/Matches.js.map +0 -1
  135. package/dist/esm/RouterProvider.d.ts +0 -10
  136. package/dist/esm/RouterProvider.js +0 -33
  137. package/dist/esm/RouterProvider.js.map +0 -1
  138. package/dist/esm/SafeFragment.d.ts +0 -1
  139. package/dist/esm/SafeFragment.js +0 -8
  140. package/dist/esm/SafeFragment.js.map +0 -1
  141. package/dist/esm/ScriptOnce.d.ts +0 -5
  142. package/dist/esm/ScriptOnce.js +0 -28
  143. package/dist/esm/ScriptOnce.js.map +0 -1
  144. package/dist/esm/Scripts.d.ts +0 -1
  145. package/dist/esm/Scripts.js +0 -51
  146. package/dist/esm/Scripts.js.map +0 -1
  147. package/dist/esm/ScrollRestoration.d.ts +0 -14
  148. package/dist/esm/ScrollRestoration.js +0 -39
  149. package/dist/esm/ScrollRestoration.js.map +0 -1
  150. package/dist/esm/Transitioner.d.ts +0 -1
  151. package/dist/esm/Transitioner.js +0 -98
  152. package/dist/esm/Transitioner.js.map +0 -1
  153. package/dist/esm/awaited.d.ts +0 -10
  154. package/dist/esm/awaited.js +0 -31
  155. package/dist/esm/awaited.js.map +0 -1
  156. package/dist/esm/fileRoute.d.ts +0 -54
  157. package/dist/esm/fileRoute.js +0 -107
  158. package/dist/esm/fileRoute.js.map +0 -1
  159. package/dist/esm/history.d.ts +0 -8
  160. package/dist/esm/index.d.ts +0 -55
  161. package/dist/esm/index.js +0 -151
  162. package/dist/esm/index.js.map +0 -1
  163. package/dist/esm/lazyRouteComponent.d.ts +0 -2
  164. package/dist/esm/lazyRouteComponent.js +0 -61
  165. package/dist/esm/lazyRouteComponent.js.map +0 -1
  166. package/dist/esm/link.d.ts +0 -48
  167. package/dist/esm/link.js +0 -307
  168. package/dist/esm/link.js.map +0 -1
  169. package/dist/esm/matchContext.d.ts +0 -3
  170. package/dist/esm/matchContext.js +0 -10
  171. package/dist/esm/matchContext.js.map +0 -1
  172. package/dist/esm/not-found.d.ts +0 -9
  173. package/dist/esm/not-found.js +0 -40
  174. package/dist/esm/not-found.js.map +0 -1
  175. package/dist/esm/renderRouteNotFound.d.ts +0 -2
  176. package/dist/esm/renderRouteNotFound.js +0 -22
  177. package/dist/esm/renderRouteNotFound.js.map +0 -1
  178. package/dist/esm/route.d.ts +0 -95
  179. package/dist/esm/route.js +0 -205
  180. package/dist/esm/route.js.map +0 -1
  181. package/dist/esm/router.d.ts +0 -72
  182. package/dist/esm/router.js +0 -22
  183. package/dist/esm/router.js.map +0 -1
  184. package/dist/esm/routerContext.d.ts +0 -8
  185. package/dist/esm/routerContext.js +0 -16
  186. package/dist/esm/routerContext.js.map +0 -1
  187. package/dist/esm/scroll-restoration.d.ts +0 -1
  188. package/dist/esm/scroll-restoration.js +0 -24
  189. package/dist/esm/scroll-restoration.js.map +0 -1
  190. package/dist/esm/serializer.d.ts +0 -6
  191. package/dist/esm/structuralSharing.d.ts +0 -8
  192. package/dist/esm/typePrimitives.d.ts +0 -16
  193. package/dist/esm/useBlocker.d.ts +0 -66
  194. package/dist/esm/useBlocker.js +0 -148
  195. package/dist/esm/useBlocker.js.map +0 -1
  196. package/dist/esm/useCanGoBack.d.ts +0 -1
  197. package/dist/esm/useCanGoBack.js +0 -8
  198. package/dist/esm/useCanGoBack.js.map +0 -1
  199. package/dist/esm/useLoaderData.d.ts +0 -8
  200. package/dist/esm/useLoaderData.js +0 -15
  201. package/dist/esm/useLoaderData.js.map +0 -1
  202. package/dist/esm/useLoaderDeps.d.ts +0 -8
  203. package/dist/esm/useLoaderDeps.js +0 -14
  204. package/dist/esm/useLoaderDeps.js.map +0 -1
  205. package/dist/esm/useLocation.d.ts +0 -7
  206. package/dist/esm/useLocation.js +0 -10
  207. package/dist/esm/useLocation.js.map +0 -1
  208. package/dist/esm/useMatch.d.ts +0 -10
  209. package/dist/esm/useMatch.js +0 -30
  210. package/dist/esm/useMatch.js.map +0 -1
  211. package/dist/esm/useNavigate.d.ts +0 -5
  212. package/dist/esm/useNavigate.js +0 -38
  213. package/dist/esm/useNavigate.js.map +0 -1
  214. package/dist/esm/useParams.d.ts +0 -9
  215. package/dist/esm/useParams.js +0 -16
  216. package/dist/esm/useParams.js.map +0 -1
  217. package/dist/esm/useRouteContext.d.ts +0 -3
  218. package/dist/esm/useRouteContext.js +0 -11
  219. package/dist/esm/useRouteContext.js.map +0 -1
  220. package/dist/esm/useRouter.d.ts +0 -4
  221. package/dist/esm/useRouter.js +0 -15
  222. package/dist/esm/useRouter.js.map +0 -1
  223. package/dist/esm/useRouterState.d.ts +0 -8
  224. package/dist/esm/useRouterState.js +0 -29
  225. package/dist/esm/useRouterState.js.map +0 -1
  226. package/dist/esm/useSearch.d.ts +0 -9
  227. package/dist/esm/useSearch.js +0 -16
  228. package/dist/esm/useSearch.js.map +0 -1
  229. package/dist/esm/utils.d.ts +0 -49
  230. package/dist/esm/utils.js +0 -55
  231. package/dist/esm/utils.js.map +0 -1
  232. package/dist/llms/index.d.ts +0 -3
  233. package/dist/llms/index.js +0 -35
  234. package/dist/llms/rules/api.d.ts +0 -2
  235. package/dist/llms/rules/api.js +0 -4241
  236. package/dist/llms/rules/guide.d.ts +0 -2
  237. package/dist/llms/rules/guide.js +0 -6225
  238. package/dist/llms/rules/routing.d.ts +0 -2
  239. package/dist/llms/rules/routing.js +0 -1946
  240. package/dist/llms/rules/setup-and-architecture.d.ts +0 -2
  241. package/dist/llms/rules/setup-and-architecture.js +0 -932
@@ -1,4241 +0,0 @@
1
- export default `# ActiveLinkOptions type
2
-
3
- The \`ActiveLinkOptions\` type extends the [\`LinkOptions\`](../LinkOptionsType.md) type and contains additional options that can be used to describe how a link should be styled when it is active.
4
-
5
- \`\`\`tsx
6
- type ActiveLinkOptions = LinkOptions & {
7
- activeProps?:
8
- | React.AnchorHTMLAttributes<HTMLAnchorElement>
9
- | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
10
- inactiveProps?:
11
- | React.AnchorHTMLAttributes<HTMLAnchorElement>
12
- | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
13
- }
14
- \`\`\`
15
-
16
- ## ActiveLinkOptions properties
17
-
18
- The \`ActiveLinkOptions\` object accepts/contains the following properties:
19
-
20
- ### \`activeProps\`
21
-
22
- - \`React.AnchorHTMLAttributes<HTMLAnchorElement>\`
23
- - Optional
24
- - The props that will be applied to the anchor element when the link is active
25
-
26
- ### \`inactiveProps\`
27
-
28
- - Type: \`React.AnchorHTMLAttributes<HTMLAnchorElement>\`
29
- - Optional
30
- - The props that will be applied to the anchor element when the link is inactive
31
-
32
- # AsyncRouteComponent type
33
-
34
- The \`AsyncRouteComponent\` type is used to describe a code-split route component that can be preloaded using a \`component.preload()\` method.
35
-
36
- \`\`\`tsx
37
- type AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {
38
- preload?: () => Promise<void>
39
- }
40
- \`\`\`
41
-
42
- # FileRoute class
43
-
44
- > [!CAUTION]
45
- > This class has been deprecated and will be removed in the next major version of TanStack Router.
46
- > Please use the [\`createFileRoute\`](../createFileRouteFunction.md) function instead.
47
-
48
- The \`FileRoute\` class is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the \`tsr generate\` and \`tsr watch\` commands.
49
-
50
- ## \`FileRoute\` constructor
51
-
52
- The \`FileRoute\` constructor accepts a single argument: the \`path\` of the file that the route will be generated for.
53
-
54
- ### Constructor options
55
-
56
- - Type: \`string\` literal
57
- - Required, but **automatically inserted and updated by the \`tsr generate\` and \`tsr watch\` commands**.
58
- - The full path of the file that the route will be generated from.
59
-
60
- ### Constructor returns
61
-
62
- - An instance of the \`FileRoute\` class that can be used to create a route.
63
-
64
- ## \`FileRoute\` methods
65
-
66
- The \`FileRoute\` class implements the following method(s):
67
-
68
- ### \`.createRoute\` method
69
-
70
- The \`createRoute\` method is a method that can be used to configure the file route instance. It accepts a single argument: the \`options\` that will be used to configure the file route instance.
71
-
72
- #### .createRoute options
73
-
74
- - Type: \`Omit<RouteOptions, 'getParentRoute' | 'path' | 'id'>\`
75
- - [\`RouteOptions\`](../RouteOptionsType.md)
76
- - Optional
77
- - The same options that are available to the \`Route\` class, but with the \`getParentRoute\`, \`path\`, and \`id\` options omitted since they are unnecessary for file-based routing.
78
-
79
- #### .createRoute returns
80
-
81
- A [\`Route\`](../RouteType.md) instance that can be used to configure the route to be inserted into the route-tree.
82
-
83
- > ⚠️ Note: For \`tsr generate\` and \`tsr watch\` to work properly, the file route instance must be exported from the file using the \`Route\` identifier.
84
-
85
- ### Examples
86
-
87
- \`\`\`tsx
88
- import { FileRoute } from '@tanstack/react-router'
89
-
90
- export const Route = new FileRoute('/').createRoute({
91
- loader: () => {
92
- return 'Hello World'
93
- },
94
- component: IndexComponent,
95
- })
96
-
97
- function IndexComponent() {
98
- const data = Route.useLoaderData()
99
- return <div>{data}</div>
100
- }
101
- \`\`\`
102
-
103
- # LinkOptions type
104
-
105
- The \`LinkOptions\` type extends the [\`NavigateOptions\`](../NavigateOptionsType.md) type and contains additional options that can be used by TanStack Router when handling actual anchor element attributes.
106
-
107
- \`\`\`tsx
108
- type LinkOptions = NavigateOptions & {
109
- target?: HTMLAnchorElement['target']
110
- activeOptions?: ActiveOptions
111
- preload?: false | 'intent'
112
- preloadDelay?: number
113
- disabled?: boolean
114
- }
115
- \`\`\`
116
-
117
- ## LinkOptions properties
118
-
119
- The \`LinkOptions\` object accepts/contains the following properties:
120
-
121
- ### \`target\`
122
-
123
- - Type: \`HTMLAnchorElement['target']\`
124
- - Optional
125
- - The standard anchor tag target attribute
126
-
127
- ### \`activeOptions\`
128
-
129
- - Type: \`ActiveOptions\`
130
- - Optional
131
- - The options that will be used to determine if the link is active
132
-
133
- ### \`preload\`
134
-
135
- - Type: \`false | 'intent' | 'viewport' | 'render'\`
136
- - Optional
137
- - If set, the link's preloading strategy will be set to this value.
138
- - See the [Preloading guide](../../../guide/preloading.md) for more information.
139
-
140
- ### \`preloadDelay\`
141
-
142
- - Type: \`number\`
143
- - Optional
144
- - Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled.
145
-
146
- ### \`disabled\`
147
-
148
- - Type: \`boolean\`
149
- - Optional
150
- - If true, will render the link without the href attribute
151
-
152
- # LinkProps type
153
-
154
- The \`LinkProps\` type extends the [\`ActiveLinkOptions\`](../ActiveLinkOptionsType.md) and \`React.AnchorHTMLAttributes<HTMLAnchorElement>\` types and contains additional props specific to the \`Link\` component.
155
-
156
- \`\`\`tsx
157
- type LinkProps = ActiveLinkOptions &
158
- Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'> & {
159
- children?:
160
- | React.ReactNode
161
- | ((state: { isActive: boolean }) => React.ReactNode)
162
- }
163
- \`\`\`
164
-
165
- ## LinkProps properties
166
-
167
- - All of the props from [\`ActiveLinkOptions\`](../ActiveLinkOptionsType.md)
168
- - All of the props from \`React.AnchorHTMLAttributes<HTMLAnchorElement>\`
169
-
170
- #### \`children\`
171
-
172
- - Type: \`React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode)\`
173
- - Optional
174
- - The children that will be rendered inside of the anchor element. If a function is provided, it will be called with an object that contains the \`isActive\` boolean value that can be used to determine if the link is active.
175
-
176
- # MatchRouteOptions type
177
-
178
- The \`MatchRouteOptions\` type is used to describe the options that can be used when matching a route.
179
-
180
- \`\`\`tsx
181
- interface MatchRouteOptions {
182
- pending?: boolean
183
- caseSensitive?: boolean
184
- includeSearch?: boolean
185
- fuzzy?: boolean
186
- }
187
- \`\`\`
188
-
189
- ## MatchRouteOptions properties
190
-
191
- The \`MatchRouteOptions\` type has the following properties:
192
-
193
- ### \`pending\` property
194
-
195
- - Type: \`boolean\`
196
- - Optional
197
- - If \`true\`, will match against pending location instead of the current location
198
-
199
- ### \`caseSensitive\` property
200
-
201
- - Type: \`boolean\`
202
- - Optional
203
- - If \`true\`, will match against the current location with case sensitivity
204
-
205
- ### \`includeSearch\` property
206
-
207
- - Type: \`boolean\`
208
- - Optional
209
- - If \`true\`, will match against the current location's search params using a deep inclusive check. e.g. \`{ a: 1 }\` will match for a current location of \`{ a: 1, b: 2 }\`
210
-
211
- ### \`fuzzy\` property
212
-
213
- - Type: \`boolean\`
214
- - Optional
215
- - If \`true\`, will match against the current location using a fuzzy match. e.g. \`/posts\` will match for a current location of \`/posts/123\`
216
-
217
- # NavigateOptions type
218
-
219
- The \`NavigateOptions\` type is used to describe the options that can be used when describing a navigation action in TanStack Router.
220
-
221
- \`\`\`tsx
222
- type NavigateOptions = ToOptions & {
223
- replace?: boolean
224
- resetScroll?: boolean
225
- hashScrollIntoView?: boolean | ScrollIntoViewOptions
226
- viewTransition?: boolean | ViewTransitionOptions
227
- ignoreBlocker?: boolean
228
- reloadDocument?: boolean
229
- href?: string
230
- }
231
- \`\`\`
232
-
233
- ## NavigateOptions properties
234
-
235
- The \`NavigateOptions\` object accepts the following properties:
236
-
237
- ### \`replace\`
238
-
239
- - Type: \`boolean\`
240
- - Optional
241
- - Defaults to \`false\`.
242
- - If \`true\`, the location will be committed to the browser history using \`history.replace\` instead of \`history.push\`.
243
-
244
- ### \`resetScroll\`
245
-
246
- - Type: \`boolean\`
247
- - Optional
248
- - Defaults to \`true\` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.
249
- - If \`false\`, the scroll position will not be reset to 0,0 after the location is committed to history.
250
-
251
- ### \`hashScrollIntoView\`
252
-
253
- - Type: \`boolean | ScrollIntoViewOptions\`
254
- - Optional
255
- - Defaults to \`true\` so the element with an id matching the hash will be scrolled into view after the location is committed to history.
256
- - If \`false\`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.
257
- - If an object is provided, it will be passed to the \`scrollIntoView\` method as options.
258
- - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on \`ScrollIntoViewOptions\`.
259
-
260
- ### \`viewTransition\`
261
-
262
- - Type: \`boolean | ViewTransitionOptions\`
263
- - Optional
264
- - Defaults to \`false\`.
265
- - If \`true\`, navigation will be called using \`document.startViewTransition()\`.
266
- - If [\`ViewTransitionOptions\`](../ViewTransitionOptionsType.md), route navigations will be called using \`document.startViewTransition({update, types})\` where \`types\` will be the strings array passed with \`ViewTransitionOptions["types"]\`. If the browser does not support viewTransition types, the navigation will fall back to normal \`document.startTransition()\`, same as if \`true\` was passed.
267
- - If the browser does not support this api, this option will be ignored.
268
- - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
269
- - See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types
270
-
271
- ### \`ignoreBlocker\`
272
-
273
- - Type: \`boolean\`
274
- - Optional
275
- - Defaults to \`false\`.
276
- - If \`true\`, navigation will ignore any blockers that might prevent it.
277
-
278
- ### \`reloadDocument\`
279
-
280
- - Type: \`boolean\`
281
- - Optional
282
- - Defaults to \`false\`.
283
- - If \`true\`, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.
284
-
285
- ### \`href\`
286
-
287
- - Type: \`string\`
288
- - Optional
289
- - This can be used instead of \`to\` to navigate to a fully built href, e.g. pointing to an external target.
290
-
291
- - [\`ToOptions\`](../ToOptionsType.md)
292
-
293
- # NotFoundError
294
-
295
- The \`NotFoundError\` type is used to represent a not-found error in TanStack Router.
296
-
297
- \`\`\`tsx
298
- export type NotFoundError = {
299
- global?: boolean
300
- data?: any
301
- throw?: boolean
302
- routeId?: string
303
- }
304
- \`\`\`
305
-
306
- ## NotFoundError properties
307
-
308
- The \`NotFoundError\` object accepts/contains the following properties:
309
-
310
- ### \`data\` property
311
-
312
- - Type: \`any\`
313
- - Optional
314
- - Custom data that is passed into to \`notFoundComponent\` when the not-found error is handled
315
-
316
- ### \`global\` property
317
-
318
- - Type: \`boolean\`
319
- - Optional - \`default: false\`
320
- - If true, the not-found error will be handled by the \`notFoundComponent\` of the root route instead of bubbling up from the route that threw it. This has the same behavior as importing the root route and calling \`RootRoute.notFound()\`.
321
-
322
- ### \`route\` property
323
-
324
- - Type: \`string\`
325
- - Optional
326
- - The ID of the route that will attempt to handle the not-found error. If the route does not have a \`notFoundComponent\`, the error will bubble up to the parent route (and be handled by the root route if necessary). By default, TanStack Router will attempt to handle the not-found error with the route that threw it.
327
-
328
- ### \`throw\` property
329
-
330
- - Type: \`boolean\`
331
- - Optional - \`default: false\`
332
- - If provided, will throw the not-found object instead of returning it. This can be useful in places where \`throwing\` in a function might cause it to have a return type of \`never\`. In that case, you can use \`notFound({ throw: true })\` to throw the not-found object instead of returning it.
333
-
334
- # NotFoundRoute class
335
-
336
- > [!CAUTION]
337
- > This class has been deprecated and will be removed in the next major version of TanStack Router.
338
- > Please use the \`notFoundComponent\` route option that is present during route configuration.
339
- > See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.
340
-
341
- The \`NotFoundRoute\` class extends the \`Route\` class and can be used to create a not found route instance. A not found route instance can be passed to the \`routerOptions.notFoundRoute\` option to configure a default not-found/404 route for every branch of the route tree.
342
-
343
- ## Constructor options
344
-
345
- The \`NotFoundRoute\` constructor accepts an object as its only argument.
346
-
347
- - Type:
348
-
349
- \`\`\`tsx
350
- Omit<
351
- RouteOptions,
352
- | 'path'
353
- | 'id'
354
- | 'getParentRoute'
355
- | 'caseSensitive'
356
- | 'parseParams'
357
- | 'stringifyParams'
358
- >
359
- \`\`\`
360
-
361
- - [RouteOptions](../RouteOptionsType.md)
362
- - Required
363
- - The options that will be used to configure the not found route instance.
364
-
365
- ## Examples
366
-
367
- \`\`\`tsx
368
- import { NotFoundRoute, createRouter } from '@tanstack/react-router'
369
- import { Route as rootRoute } from './routes/__root'
370
- import { routeTree } from './routeTree.gen'
371
-
372
- const notFoundRoute = new NotFoundRoute({
373
- getParentRoute: () => rootRoute,
374
- component: () => <div>Not found!!!</div>,
375
- })
376
-
377
- const router = createRouter({
378
- routeTree,
379
- notFoundRoute,
380
- })
381
-
382
- // ... other code
383
- \`\`\`
384
-
385
- # ParsedHistoryState type
386
-
387
- The \`ParsedHistoryState\` type represents a parsed state object. Additionally to \`HistoryState\`, it contains the index and the unique key of the route.
388
-
389
- \`\`\`tsx
390
- export type ParsedHistoryState = HistoryState & {
391
- key?: string
392
- __TSR_index: number
393
- }
394
- \`\`\`
395
-
396
- # ParsedLocation type
397
-
398
- The \`ParsedLocation\` type represents a parsed location in TanStack Router. It contains a lot of useful information about the current location, including the pathname, search params, hash, location state, and route masking information.
399
-
400
- \`\`\`tsx
401
- interface ParsedLocation {
402
- href: string
403
- pathname: string
404
- search: TFullSearchSchema
405
- searchStr: string
406
- state: ParsedHistoryState
407
- hash: string
408
- maskedLocation?: ParsedLocation
409
- unmaskOnReload?: boolean
410
- }
411
- \`\`\`
412
-
413
- # Redirect type
414
-
415
- The \`Redirect\` type is used to represent a redirect action in TanStack Router.
416
-
417
- \`\`\`tsx
418
- export type Redirect = {
419
- statusCode?: number
420
- throw?: any
421
- headers?: HeadersInit
422
- } & NavigateOptions
423
- \`\`\`
424
-
425
- - [\`NavigateOptions\`](../NavigateOptionsType.md)
426
-
427
- ## Redirect properties
428
-
429
- The \`Redirect\` object accepts/contains the following properties:
430
-
431
- ### \`statusCode\` property
432
-
433
- - Type: \`number\`
434
- - Optional
435
- - The HTTP status code to use when redirecting
436
-
437
- ### \`throw\` property
438
-
439
- - Type: \`any\`
440
- - Optional
441
- - If provided, will throw the redirect object instead of returning it. This can be useful in places where \`throwing\` in a function might cause it to have a return type of \`never\`. In that case, you can use \`redirect({ throw: true })\` to throw the redirect object instead of returning it.
442
-
443
- ### \`headers\` property
444
-
445
- - Type: \`HeadersInit\`
446
- - Optional
447
- - The HTTP headers to use when redirecting.
448
-
449
- # Register type
450
-
451
- This type is used to register a route tree with a router instance. Doing so unlocks the full type safety of TanStack Router, including top-level exports from the \`@tanstack/react-router\` package.
452
-
453
- \`\`\`tsx
454
- export type Register = {
455
- // router: [Your router type here]
456
- }
457
- \`\`\`
458
-
459
- To register a route tree with a router instance, use declaration merging to add the type of your router instance to the Register interface under the \`router\` property:
460
-
461
- ## Examples
462
-
463
- \`\`\`tsx
464
- const router = createRouter({
465
- // ...
466
- })
467
-
468
- declare module '@tanstack/react-router' {
469
- interface Register {
470
- router: typeof router
471
- }
472
- }
473
- \`\`\`
474
-
475
- # RootRoute class
476
-
477
- > [!CAUTION]
478
- > This class has been deprecated and will be removed in the next major version of TanStack Router.
479
- > Please use the [\`createRootRoute\`](../createRootRouteFunction.md) function instead.
480
-
481
- The \`RootRoute\` class extends the \`Route\` class and can be used to create a root route instance. A root route instance can then be used to create a route tree.
482
-
483
- ## \`RootRoute\` constructor
484
-
485
- The \`RootRoute\` constructor accepts an object as its only argument.
486
-
487
- ### Constructor options
488
-
489
- The options that will be used to configure the root route instance.
490
-
491
- - Type:
492
-
493
- \`\`\`tsx
494
- Omit<
495
- RouteOptions,
496
- | 'path'
497
- | 'id'
498
- | 'getParentRoute'
499
- | 'caseSensitive'
500
- | 'parseParams'
501
- | 'stringifyParams'
502
- >
503
- \`\`\`
504
-
505
- - [\`RouteOptions\`](../RouteOptionsType.md)
506
- - Optional
507
-
508
- ## Constructor returns
509
-
510
- A new [\`Route\`](../RouteType.md) instance.
511
-
512
- ## Examples
513
-
514
- \`\`\`tsx
515
- import { RootRoute, createRouter, Outlet } from '@tanstack/react-router'
516
-
517
- const rootRoute = new RootRoute({
518
- component: () => <Outlet />,
519
- // ... root route options
520
- })
521
-
522
- const routeTree = rootRoute.addChildren([
523
- // ... other routes
524
- ])
525
-
526
- const router = createRouter({
527
- routeTree,
528
- })
529
- \`\`\`
530
-
531
- # RouteApi class
532
-
533
- > [!CAUTION]
534
- > This class has been deprecated and will be removed in the next major version of TanStack Router.
535
- > Please use the [\`getRouteApi\`](../getRouteApiFunction.md) function instead.
536
-
537
- The \`RouteApi\` class provides type-safe version of common hooks like \`useParams\`, \`useSearch\`, \`useRouteContext\`, \`useNavigate\`, \`useLoaderData\`, and \`useLoaderDeps\` that are pre-bound to a specific route ID and corresponding registered route types.
538
-
539
- ## Constructor options
540
-
541
- The \`RouteApi\` constructor accepts a single argument: the \`options\` that will be used to configure the \`RouteApi\` instance.
542
-
543
- ### \`opts.routeId\` option
544
-
545
- - Type: \`string\`
546
- - Required
547
- - The route ID to which the \`RouteApi\` instance will be bound
548
-
549
- ## Constructor returns
550
-
551
- - An instance of the [\`RouteApi\`](../RouteApiType.md) that is pre-bound to the route ID that it was called with.
552
-
553
- ## Examples
554
-
555
- \`\`\`tsx
556
- import { RouteApi } from '@tanstack/react-router'
557
-
558
- const routeApi = new RouteApi({ id: '/posts' })
559
-
560
- export function PostsPage() {
561
- const posts = routeApi.useLoaderData()
562
- // ...
563
- }
564
- \`\`\`
565
-
566
- # RouteApi Type
567
-
568
- The \`RouteApi\` describes an instance that provides type-safe versions of common hooks like \`useParams\`, \`useSearch\`, \`useRouteContext\`, \`useNavigate\`, \`useLoaderData\`, and \`useLoaderDeps\` that are pre-bound to a specific route ID and corresponding registered route types.
569
-
570
- ## \`RouteApi\` properties and methods
571
-
572
- The \`RouteApi\` has the following properties and methods:
573
-
574
- ### \`useMatch\` method
575
-
576
- \`\`\`tsx
577
- useMatch<TSelected = TAllContext>(opts?: {
578
- select?: (match: TAllContext) => TSelected
579
- }): TSelected
580
- \`\`\`
581
-
582
- - A type-safe version of the [\`useMatch\`](../useMatchHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
583
- - Options
584
- - \`opts.select\`
585
- - Optional
586
- - \`(match: RouteMatch) => TSelected\`
587
- - If supplied, this function will be called with the route match and the return value will be returned from \`useMatch\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
588
- - \`opts.structuralSharing\`
589
- - Optional
590
- - \`boolean\`
591
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
592
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
593
- - Returns
594
- - If a \`select\` function is provided, the return value of the \`select\` function.
595
- - If no \`select\` function is provided, the \`RouteMatch\` object or a loosened version of the \`RouteMatch\` object if \`opts.strict\` is \`false\`.
596
-
597
- ### \`useRouteContext\` method
598
-
599
- \`\`\`tsx
600
- useRouteContext<TSelected = TAllContext>(opts?: {
601
- select?: (search: TAllContext) => TSelected
602
- }): TSelected
603
- \`\`\`
604
-
605
- - A type-safe version of the [\`useRouteContext\`](../useRouteContextHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
606
- - Options
607
- - \`opts.select\`
608
- - Optional
609
- - \`(match: RouteContext) => TSelected\`
610
- - If supplied, this function will be called with the route match and the return value will be returned from \`useRouteContext\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
611
- - Returns
612
- - If a \`select\` function is provided, the return value of the \`select\` function.
613
- - If no \`select\` function is provided, the \`RouteContext\` object or a loosened version of the \`RouteContext\` object if \`opts.strict\` is \`false\`.
614
-
615
- ### \`useSearch\` method
616
-
617
- \`\`\`tsx
618
- useSearch<TSelected = TFullSearchSchema>(opts?: {
619
- select?: (search: TFullSearchSchema) => TSelected
620
- }): TSelected
621
- \`\`\`
622
-
623
- - A type-safe version of the [\`useSearch\`](../useSearchHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
624
- - Options
625
- - \`opts.select\`
626
- - Optional
627
- - \`(match: TFullSearchSchema) => TSelected\`
628
- - If supplied, this function will be called with the route match and the return value will be returned from \`useSearch\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
629
- - \`opts.structuralSharing\`
630
- - Optional
631
- - \`boolean\`
632
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
633
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
634
- - Returns
635
- - If a \`select\` function is provided, the return value of the \`select\` function.
636
- - If no \`select\` function is provided, the \`TFullSearchSchema\` object or a loosened version of the \`TFullSearchSchema\` object if \`opts.strict\` is \`false\`.
637
-
638
- ### \`useParams\` method
639
-
640
- \`\`\`tsx
641
- useParams<TSelected = TAllParams>(opts?: {
642
- select?: (params: TAllParams) => TSelected
643
- }): TSelected
644
- \`\`\`
645
-
646
- - A type-safe version of the [\`useParams\`](../useParamsHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
647
- - Options
648
- - \`opts.select\`
649
- - Optional
650
- - \`(match: TAllParams) => TSelected\`
651
- - If supplied, this function will be called with the route match and the return value will be returned from \`useParams\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
652
- - \`opts.structuralSharing\`
653
- - Optional
654
- - \`boolean\`
655
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
656
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
657
- - Returns
658
- - If a \`select\` function is provided, the return value of the \`select\` function.
659
- - If no \`select\` function is provided, the \`TAllParams\` object or a loosened version of the \`TAllParams\` object if \`opts.strict\` is \`false\`.
660
-
661
- ### \`useLoaderData\` method
662
-
663
- \`\`\`tsx
664
- useLoaderData<TSelected = TLoaderData>(opts?: {
665
- select?: (search: TLoaderData) => TSelected
666
- }): TSelected
667
- \`\`\`
668
-
669
- - A type-safe version of the [\`useLoaderData\`](../useLoaderDataHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
670
- - Options
671
- - \`opts.select\`
672
- - Optional
673
- - \`(match: TLoaderData) => TSelected\`
674
- - If supplied, this function will be called with the route match and the return value will be returned from \`useLoaderData\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
675
- - \`opts.structuralSharing\`
676
- - Optional
677
- - \`boolean\`
678
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
679
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
680
- - Returns
681
- - If a \`select\` function is provided, the return value of the \`select\` function.
682
- - If no \`select\` function is provided, the \`TLoaderData\` object or a loosened version of the \`TLoaderData\` object if \`opts.strict\` is \`false\`.
683
-
684
- ### \`useLoaderDeps\` method
685
-
686
- \`\`\`tsx
687
- useLoaderDeps<TSelected = TLoaderDeps>(opts?: {
688
- select?: (search: TLoaderDeps) => TSelected
689
- }): TSelected
690
- \`\`\`
691
-
692
- - A type-safe version of the [\`useLoaderDeps\`](../useLoaderDepsHook.md) hook that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
693
- - Options
694
- - \`opts.select\`
695
- - Optional
696
- - \`(match: TLoaderDeps) => TSelected\`
697
- - If supplied, this function will be called with the route match and the return value will be returned from \`useLoaderDeps\`.
698
- - \`opts.structuralSharing\`
699
- - Optional
700
- - \`boolean\`
701
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
702
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
703
- - Returns
704
- - If a \`select\` function is provided, the return value of the \`select\` function.
705
- - If no \`select\` function is provided, the \`TLoaderDeps\` object.
706
-
707
- ### \`useNavigate\` method
708
-
709
- \`\`\`tsx
710
- useNavigate(): // navigate function
711
- \`\`\`
712
-
713
- - A type-safe version of [\`useNavigate\`](../useNavigateHook.md) that is pre-bound to the route ID that the \`RouteApi\` instance was created with.
714
-
715
- # Route class
716
-
717
- > [!CAUTION]
718
- > This class has been deprecated and will be removed in the next major version of TanStack Router.
719
- > Please use the [\`createRoute\`](../createRouteFunction.md) function instead.
720
-
721
- The \`Route\` class implements the \`RouteApi\` class and can be used to create route instances. A route instance can then be used to create a route tree.
722
-
723
- ## \`Route\` constructor
724
-
725
- The \`Route\` constructor accepts an object as its only argument.
726
-
727
- ### Constructor options
728
-
729
- - Type: [\`RouteOptions\`](../RouteOptionsType.md)
730
- - Required
731
- - The options that will be used to configure the route instance
732
-
733
- ### Constructor returns
734
-
735
- A new [\`Route\`](../RouteType.md) instance.
736
-
737
- ## Examples
738
-
739
- \`\`\`tsx
740
- import { Route } from '@tanstack/react-router'
741
- import { rootRoute } from './__root'
742
-
743
- const indexRoute = new Route({
744
- getParentRoute: () => rootRoute,
745
- path: '/',
746
- loader: () => {
747
- return 'Hello World'
748
- },
749
- component: IndexComponent,
750
- })
751
-
752
- function IndexComponent() {
753
- const data = indexRoute.useLoaderData()
754
- return <div>{data}</div>
755
- }
756
- \`\`\`
757
-
758
- # RouteMask type
759
-
760
- The \`RouteMask\` type extends the [\`ToOptions\`](../ToOptionsType.md) type and has other the necessary properties to create a route mask.
761
-
762
- ## RouteMask properties
763
-
764
- The \`RouteMask\` type accepts an object with the following properties:
765
-
766
- ### \`...ToOptions\`
767
-
768
- - Type: [\`ToOptions\`](../ToOptionsType.md)
769
- - Required
770
- - The options that will be used to configure the route mask
771
-
772
- ### \`options.routeTree\`
773
-
774
- - Type: \`TRouteTree\`
775
- - Required
776
- - The route tree that this route mask will support
777
-
778
- ### \`options.unmaskOnReload\`
779
-
780
- - Type: \`boolean\`
781
- - Optional
782
- - If \`true\`, the route mask will be removed when the page is reloaded
783
-
784
- # RouteMatch type
785
-
786
- The \`RouteMatch\` type represents a route match in TanStack Router.
787
-
788
- \`\`\`tsx
789
- interface RouteMatch {
790
- id: string
791
- routeId: string
792
- pathname: string
793
- params: Route['allParams']
794
- status: 'pending' | 'success' | 'error'
795
- isFetching: boolean
796
- showPending: boolean
797
- error: unknown
798
- paramsError: unknown
799
- searchError: unknown
800
- updatedAt: number
801
- loadPromise?: Promise<void>
802
- loaderData?: Route['loaderData']
803
- context: Route['allContext']
804
- search: Route['fullSearchSchema']
805
- fetchedAt: number
806
- abortController: AbortController
807
- cause: 'enter' | 'stay'
808
- }
809
- \`\`\`
810
-
811
- # RouteOptions type
812
-
813
- The \`RouteOptions\` type is used to describe the options that can be used when creating a route.
814
-
815
- ## RouteOptions properties
816
-
817
- The \`RouteOptions\` type accepts an object with the following properties:
818
-
819
- ### \`getParentRoute\` method
820
-
821
- - Type: \`() => TParentRoute\`
822
- - Required
823
- - A function that returns the parent route of the route being created. This is required to provide full type safety to child route configurations and to ensure that the route tree is built correctly.
824
-
825
- ### \`path\` property
826
-
827
- - Type: \`string\`
828
- - Required, unless an \`id\` is provided to configure the route as a pathless layout route
829
- - The path segment that will be used to match the route.
830
-
831
- ### \`id\` property
832
-
833
- - Type: \`string\`
834
- - Optional, but required if a \`path\` is not provided
835
- - The unique identifier for the route if it is to be configured as a pathless layout route. If provided, the route will not match against the location pathname and its routes will be flattened into its parent route for matching.
836
-
837
- ### \`component\` property
838
-
839
- - Type: \`RouteComponent\` or \`LazyRouteComponent\`
840
- - Optional - Defaults to \`<Outlet />\`
841
- - The content to be rendered when the route is matched.
842
-
843
- ### \`errorComponent\` property
844
-
845
- - Type: \`RouteComponent\` or \`LazyRouteComponent\`
846
- - Optional - Defaults to \`routerOptions.defaultErrorComponent\`
847
- - The content to be rendered when the route encounters an error.
848
-
849
- ### \`pendingComponent\` property
850
-
851
- - Type: \`RouteComponent\` or \`LazyRouteComponent\`
852
- - Optional - Defaults to \`routerOptions.defaultPendingComponent\`
853
- - The content to be rendered if and when the route is pending and has reached its pendingMs threshold.
854
-
855
- ### \`notFoundComponent\` property
856
-
857
- - Type: \`NotFoundRouteComponent\` or \`LazyRouteComponent\`
858
- - Optional - Defaults to \`routerOptions.defaultNotFoundComponent\`
859
- - The content to be rendered when the route is not found.
860
-
861
- ### \`validateSearch\` method
862
-
863
- - Type: \`(rawSearchParams: unknown) => TSearchSchema\`
864
- - Optional
865
- - A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router.
866
- - Optionally, the parameter type can be tagged with the \`SearchSchemaInput\` type like this: \`(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema\`. If this tag is present, \`TSearchSchemaInput\` will be used to type the \`search\` property of \`<Link />\` and \`navigate()\` **instead of** \`TSearchSchema\`. The difference between \`TSearchSchemaInput\` and \`TSearchSchema\` can be useful, for example, to express optional search parameters.
867
-
868
- ### \`search.middlewares\` property
869
-
870
- - Type: \`(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]\`
871
- - Optional
872
- - Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants.
873
- - A search middleware is passed in the current search (if it is the first middleware to run) or is invoked by the previous middleware calling \`next\`.
874
-
875
- ### \`parseParams\` method (⚠️ deprecated, use \`params.parse\` instead)
876
-
877
- - Type: \`(rawParams: Record<string, string>) => TParams\`
878
- - Optional
879
- - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
880
-
881
- ### \`stringifyParams\` method (⚠️ deprecated, use \`params.stringify\` instead)
882
-
883
- - Type: \`(params: TParams) => Record<string, string>\`
884
- - Required if \`parseParams\` is provided
885
- - A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of \`Record<string, string>\` mapping.
886
-
887
- ### \`params.parse\` method
888
-
889
- - Type: \`(rawParams: Record<string, string>) => TParams\`
890
- - Optional
891
- - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
892
-
893
- ### \`params.stringify\` method
894
-
895
- - Type: \`(params: TParams) => Record<string, string>\`
896
- - A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of \`Record<string, string>\` mapping.
897
-
898
- ### \`beforeLoad\` method
899
-
900
- - Type:
901
-
902
- \`\`\`tsx
903
- type beforeLoad = (
904
- opts: RouteMatch & {
905
- search: TFullSearchSchema
906
- abortController: AbortController
907
- preload: boolean
908
- params: TAllParams
909
- context: TParentContext
910
- location: ParsedLocation
911
- navigate: NavigateFn<AnyRoute> // @deprecated
912
- buildLocation: BuildLocationFn<AnyRoute>
913
- cause: 'enter' | 'stay'
914
- },
915
- ) => Promise<TRouteContext> | TRouteContext | void
916
- \`\`\`
917
-
918
- - Optional
919
- - [\`ParsedLocation\`](../ParsedLocationType.md)
920
- - This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the \`onError\` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.
921
- - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the \`pendingComponent\` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.
922
- - If this function returns a \`TRouteContext\` object, that object will be merged into the route's context and be made available in the \`loader\` and other related route components/methods.
923
- - It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a \`redirect\` object from this function.
924
-
925
- > 🚧 \`opts.navigate\` has been deprecated and will be removed in the next major release. Use \`throw redirect({ to: '/somewhere' })\` instead. Read more about the \`redirect\` function [here](../redirectFunction.md).
926
-
927
- ### \`loader\` method
928
-
929
- - Type:
930
-
931
- \`\`\`tsx
932
- type loader = (
933
- opts: RouteMatch & {
934
- abortController: AbortController
935
- cause: 'enter' | 'stay'
936
- context: TAllContext
937
- deps: TLoaderDeps
938
- location: ParsedLocation
939
- params: TAllParams
940
- preload: boolean
941
- parentMatchPromise: Promise<MakeRouteMatchFromRoute<TParentRoute>>
942
- navigate: NavigateFn<AnyRoute> // @deprecated
943
- },
944
- ) => Promise<TLoaderData> | TLoaderData | void
945
- \`\`\`
946
-
947
- - Optional
948
- - [\`ParsedLocation\`](../ParsedLocationType.md)
949
- - This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the \`onError\` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.
950
- - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the \`pendingComponent\` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.
951
- - If this function returns a \`TLoaderData\` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the \`useLoaderData\` hook in any component that is a child of the route match before another \`<Outlet />\` is rendered.
952
- - Deps must be returned by your \`loaderDeps\` function in order to appear.
953
-
954
- > 🚧 \`opts.navigate\` has been deprecated and will be removed in the next major release. Use \`throw redirect({ to: '/somewhere' })\` instead. Read more about the \`redirect\` function [here](../redirectFunction.md).
955
-
956
- ### \`loaderDeps\` method
957
-
958
- - Type:
959
-
960
- \`\`\`tsx
961
- type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
962
- \`\`\`
963
-
964
- - Optional
965
- - A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation.
966
- - By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.
967
- - If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the \`loader\`'s \`deps\` argument.
968
-
969
- ### \`staleTime\` property
970
-
971
- - Type: \`number\`
972
- - Optional
973
- - Defaults to \`routerOptions.defaultStaleTime\`, which defaults to \`0\`
974
- - The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded.
975
-
976
- ### \`preloadStaleTime\` property
977
-
978
- - Type: \`number\`
979
- - Optional
980
- - Defaults to \`routerOptions.defaultPreloadStaleTime\`, which defaults to \`30_000\` ms (30 seconds)
981
- - The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal \`staleTime\` is used instead.
982
-
983
- ### \`gcTime\` property
984
-
985
- - Type: \`number\`
986
- - Optional
987
- - Defaults to \`routerOptions.defaultGcTime\`, which defaults to 30 minutes.
988
- - The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use.
989
-
990
- ### \`shouldReload\` property
991
-
992
- - Type: \`boolean | ((args: LoaderArgs) => boolean)\`
993
- - Optional
994
- - If \`false\` or returns \`false\`, the route match's loader data will not be reloaded on subsequent matches.
995
- - If \`true\` or returns \`true\`, the route match's loader data will be reloaded on subsequent matches.
996
- - If \`undefined\` or returns \`undefined\`, the route match's loader data will adhere to the default stale-while-revalidate behavior.
997
-
998
- ### \`caseSensitive\` property
999
-
1000
- - Type: \`boolean\`
1001
- - Optional
1002
- - If \`true\`, this route will be matched as case-sensitive.
1003
-
1004
- ### \`wrapInSuspense\` property
1005
-
1006
- - Type: \`boolean\`
1007
- - Optional
1008
- - If \`true\`, this route will be forcefully wrapped in a suspense boundary, regardless if a reason is found to do so from inspecting its provided components.
1009
-
1010
- ### \`pendingMs\` property
1011
-
1012
- - Type: \`number\`
1013
- - Optional
1014
- - Defaults to \`routerOptions.defaultPendingMs\`, which defaults to \`1000\`
1015
- - The threshold in milliseconds that a route must be pending before its \`pendingComponent\` is shown.
1016
-
1017
- ### \`pendingMinMs\` property
1018
-
1019
- - Type: \`number\`
1020
- - Optional
1021
- - Defaults to \`routerOptions.defaultPendingMinMs\` which defaults to \`500\`
1022
- - The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second.
1023
-
1024
- ### \`preloadMaxAge\` property
1025
-
1026
- - Type: \`number\`
1027
- - Optional
1028
- - Defaults to \`30_000\` ms (30 seconds)
1029
- - The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded.
1030
-
1031
- ### \`preSearchFilters\` property (⚠️ deprecated, use \`search.middlewares\` instead)
1032
-
1033
- - Type: \`((search: TFullSearchSchema) => TFullSearchSchema)[]\`
1034
- - Optional
1035
- - An array of functions that will be called when generating any new links to this route or its grandchildren.
1036
- - Each function will be called with the current search params and should return a new search params object that will be used to generate the link.
1037
- - It has a \`pre\` prefix because it is called before the user-provided function that is passed to \`navigate\`/\`Link\` etc has a chance to modify the search params.
1038
-
1039
- ### \`postSearchFilters\` property (⚠️ deprecated, use \`search.middlewares\` instead)
1040
-
1041
- - Type: \`((search: TFullSearchSchema) => TFullSearchSchema)[]\`
1042
- - Optional
1043
- - An array of functions that will be called when generating any new links to this route or its grandchildren.
1044
- - Each function will be called with the current search params and should return a new search params object that will be used to generate the link.
1045
- - It has a \`post\` prefix because it is called after the user-provided function that is passed to \`navigate\`/\`Link\` etc has modified the search params.
1046
-
1047
- ### \`onError\` property
1048
-
1049
- - Type: \`(error: any) => void\`
1050
- - Optional
1051
- - A function that will be called when an error is thrown during a navigation or preload event.
1052
- - If this function throws a [\`redirect\`](../redirectFunction.md), then the router will process and apply the redirect immediately.
1053
-
1054
- ### \`onEnter\` property
1055
-
1056
- - Type: \`(match: RouteMatch) => void\`
1057
- - Optional
1058
- - A function that will be called when a route is matched and loaded after not being matched in the previous location.
1059
-
1060
- ### \`onStay\` property
1061
-
1062
- - Type: \`(match: RouteMatch) => void\`
1063
- - Optional
1064
- - A function that will be called when a route is matched and loaded after being matched in the previous location.
1065
-
1066
- ### \`onLeave\` property
1067
-
1068
- - Type: \`(match: RouteMatch) => void\`
1069
- - Optional
1070
- - A function that will be called when a route is no longer matched after being matched in the previous location.
1071
-
1072
- ### \`onCatch\` property
1073
-
1074
- - Type: \`(error: Error, errorInfo: ErrorInfo) => void\`
1075
- - Optional - Defaults to \`routerOptions.defaultOnCatch\`
1076
- - A function that will be called when errors are caught when the route encounters an error.
1077
-
1078
- ### \`remountDeps\` method
1079
-
1080
- - Type:
1081
-
1082
- \`\`\`tsx
1083
- type remountDeps = (opts: RemountDepsOptions) => any
1084
-
1085
- interface RemountDepsOptions<
1086
- in out TRouteId,
1087
- in out TFullSearchSchema,
1088
- in out TAllParams,
1089
- in out TLoaderDeps,
1090
- > {
1091
- routeId: TRouteId
1092
- search: TFullSearchSchema
1093
- params: TAllParams
1094
- loaderDeps: TLoaderDeps
1095
- }
1096
- \`\`\`
1097
-
1098
- - Optional
1099
- - A function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.
1100
- - The return value needs to be JSON serializable.
1101
- - By default, a route component will not be remounted if it stays active after a navigation.
1102
-
1103
- Example:
1104
- If you want to configure to remount a route component upon \`params\` change, use:
1105
-
1106
- \`\`\`tsx
1107
- remountDeps: ({ params }) => params
1108
- \`\`\`
1109
-
1110
- # Route type
1111
-
1112
- The \`Route\` type is used to describe a route instance.
1113
-
1114
- ## \`Route\` properties and methods
1115
-
1116
- An instance of the \`Route\` has the following properties and methods:
1117
-
1118
- ### \`.addChildren\` method
1119
-
1120
- - Type: \`(children: Route[]) => this\`
1121
- - Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children).
1122
-
1123
- ### \`.update\` method
1124
-
1125
- - Type: \`(options: Partial<UpdatableRouteOptions>) => this\`
1126
- - Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options).
1127
- - In some circumstances, it can be useful to update a route instance's options after it has been created to avoid circular type references.
1128
- - ...\`RouteApi\` methods
1129
-
1130
- ### \`.lazy\` method
1131
-
1132
- - Type: \`(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this\`
1133
- - Updates the route instance with a new lazy importer which will be resolved lazily when loading the route. This can be useful for code splitting.
1134
-
1135
- ### ...\`RouteApi\` methods
1136
-
1137
- - All of the methods from [\`RouteApi\`](../RouteApiType.md) are available.
1138
-
1139
- # Router Class
1140
-
1141
- > [!CAUTION]
1142
- > This class has been deprecated and will be removed in the next major version of TanStack Router.
1143
- > Please use the [\`createRouter\`](../createRouterFunction.md) function instead.
1144
-
1145
- The \`Router\` class is used to instantiate a new router instance.
1146
-
1147
- ## \`Router\` constructor
1148
-
1149
- The \`Router\` constructor accepts a single argument: the \`options\` that will be used to configure the router instance.
1150
-
1151
- ### Constructor options
1152
-
1153
- - Type: [\`RouterOptions\`](../RouterOptionsType.md)
1154
- - Required
1155
- - The options that will be used to configure the router instance.
1156
-
1157
- ### Constructor returns
1158
-
1159
- - An instance of the [\`Router\`](../RouterType.md).
1160
-
1161
- ## Examples
1162
-
1163
- \`\`\`tsx
1164
- import { Router, RouterProvider } from '@tanstack/react-router'
1165
- import { routeTree } from './routeTree.gen'
1166
-
1167
- const router = new Router({
1168
- routeTree,
1169
- defaultPreload: 'intent',
1170
- })
1171
-
1172
- export default function App() {
1173
- return <RouterProvider router={router} />
1174
- }
1175
- \`\`\`
1176
-
1177
- # RouterEvents type
1178
-
1179
- The \`RouterEvents\` type contains all of the events that the router can emit. Each top-level key of this type, represents the name of an event that the router can emit. The values of the keys are the event payloads.
1180
-
1181
- \`\`\`tsx
1182
- type RouterEvents = {
1183
- onBeforeNavigate: {
1184
- type: 'onBeforeNavigate'
1185
- fromLocation?: ParsedLocation
1186
- toLocation: ParsedLocation
1187
- pathChanged: boolean
1188
- hrefChanged: boolean
1189
- }
1190
- onBeforeLoad: {
1191
- type: 'onBeforeLoad'
1192
- fromLocation?: ParsedLocation
1193
- toLocation: ParsedLocation
1194
- pathChanged: boolean
1195
- hrefChanged: boolean
1196
- }
1197
- onLoad: {
1198
- type: 'onLoad'
1199
- fromLocation?: ParsedLocation
1200
- toLocation: ParsedLocation
1201
- pathChanged: boolean
1202
- hrefChanged: boolean
1203
- }
1204
- onResolved: {
1205
- type: 'onResolved'
1206
- fromLocation?: ParsedLocation
1207
- toLocation: ParsedLocation
1208
- pathChanged: boolean
1209
- hrefChanged: boolean
1210
- }
1211
- onBeforeRouteMount: {
1212
- type: 'onBeforeRouteMount'
1213
- fromLocation?: ParsedLocation
1214
- toLocation: ParsedLocation
1215
- pathChanged: boolean
1216
- hrefChanged: boolean
1217
- }
1218
- onInjectedHtml: {
1219
- type: 'onInjectedHtml'
1220
- promise: Promise<string>
1221
- }
1222
- onRendered: {
1223
- type: 'onRendered'
1224
- fromLocation?: ParsedLocation
1225
- toLocation: ParsedLocation
1226
- }
1227
- }
1228
- \`\`\`
1229
-
1230
- ## RouterEvents properties
1231
-
1232
- Once an event is emitted, the following properties will be present on the event payload.
1233
-
1234
- ### \`type\` property
1235
-
1236
- - Type: \`onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved\`
1237
- - The type of the event
1238
- - This is useful for discriminating between events in a listener function.
1239
-
1240
- ### \`fromLocation\` property
1241
-
1242
- - Type: [\`ParsedLocation\`](../ParsedLocationType.md)
1243
- - The location that the router is transitioning from.
1244
-
1245
- ### \`toLocation\` property
1246
-
1247
- - Type: [\`ParsedLocation\`](../ParsedLocationType.md)
1248
- - The location that the router is transitioning to.
1249
-
1250
- ### \`pathChanged\` property
1251
-
1252
- - Type: \`boolean\`
1253
- - \`true\` if the path has changed between the \`fromLocation\` and \`toLocation\`.
1254
-
1255
- ### \`hrefChanged\` property
1256
-
1257
- - Type: \`boolean\`
1258
- - \`true\` if the href has changed between the \`fromLocation\` and \`toLocation\`.
1259
-
1260
- ## Example
1261
-
1262
- \`\`\`tsx
1263
- import { createRouter } from '@tanstack/react-router'
1264
- import { routeTree } from './routeTree.gen'
1265
-
1266
- const router = createRouter({ routeTree })
1267
-
1268
- const unsub = router.subscribe('onResolved', (evt) => {
1269
- // ...
1270
- })
1271
- \`\`\`
1272
-
1273
- # RouterOptions
1274
-
1275
- The \`RouterOptions\` type contains all of the options that can be used to configure a router instance.
1276
-
1277
- ## RouterOptions properties
1278
-
1279
- The \`RouterOptions\` type accepts an object with the following properties and methods:
1280
-
1281
- ### \`routeTree\` property
1282
-
1283
- - Type: \`AnyRoute\`
1284
- - Required
1285
- - The route tree that will be used to configure the router instance.
1286
-
1287
- ### \`history\` property
1288
-
1289
- - Type: \`RouterHistory\`
1290
- - Optional
1291
- - The history object that will be used to manage the browser history. If not provided, a new \`createBrowserHistory\` instance will be created and used.
1292
-
1293
- ### \`stringifySearch\` method
1294
-
1295
- - Type: \`(search: Record<string, any>) => string\`
1296
- - Optional
1297
- - A function that will be used to stringify search params when generating links.
1298
- - Defaults to \`defaultStringifySearch\`.
1299
-
1300
- ### \`parseSearch\` method
1301
-
1302
- - Type: \`(search: string) => Record<string, any>\`
1303
- - Optional
1304
- - A function that will be used to parse search params when parsing the current location.
1305
- - Defaults to \`defaultParseSearch\`.
1306
-
1307
- ### \`search.strict\` property
1308
-
1309
- - Type: \`boolean\`
1310
- - Optional
1311
- - Defaults to \`false\`
1312
- - Configures how unknown search params (= not returned by any \`validateSearch\`) are treated.
1313
- - If \`false\`, unknown search params will be kept.
1314
- - If \`true\`, unknown search params will be removed.
1315
-
1316
- ### \`defaultPreload\` property
1317
-
1318
- - Type: \`undefined | false | 'intent' | 'viewport' | 'render'\`
1319
- - Optional
1320
- - Defaults to \`false\`
1321
- - If \`false\`, routes will not be preloaded by default in any way.
1322
- - If \`'intent'\`, routes will be preloaded by default when the user hovers over a link or a \`touchstart\` event is detected on a \`<Link>\`.
1323
- - If \`'viewport'\`, routes will be preloaded by default when they are within the viewport of the browser.
1324
- - If \`'render'\`, routes will be preloaded by default as soon as they are rendered in the DOM.
1325
-
1326
- ### \`defaultPreloadDelay\` property
1327
-
1328
- - Type: \`number\`
1329
- - Optional
1330
- - Defaults to \`50\`
1331
- - The delay in milliseconds that a route must be hovered over or touched before it is preloaded.
1332
-
1333
- ### \`defaultComponent\` property
1334
-
1335
- - Type: \`RouteComponent\`
1336
- - Optional
1337
- - Defaults to \`Outlet\`
1338
- - The default \`component\` a route should use if no component is provided.
1339
-
1340
- ### \`defaultErrorComponent\` property
1341
-
1342
- - Type: \`RouteComponent\`
1343
- - Optional
1344
- - Defaults to \`ErrorComponent\`
1345
- - The default \`errorComponent\` a route should use if no error component is provided.
1346
-
1347
- ### \`defaultNotFoundComponent\` property
1348
-
1349
- - Type: \`NotFoundRouteComponent\`
1350
- - Optional
1351
- - Defaults to \`NotFound\`
1352
- - The default \`notFoundComponent\` a route should use if no notFound component is provided.
1353
-
1354
- ### \`defaultPendingComponent\` property
1355
-
1356
- - Type: \`RouteComponent\`
1357
- - Optional
1358
- - The default \`pendingComponent\` a route should use if no pending component is provided.
1359
-
1360
- ### \`defaultPendingMs\` property
1361
-
1362
- - Type: \`number\`
1363
- - Optional
1364
- - Defaults to \`1000\`
1365
- - The default \`pendingMs\` a route should use if no pendingMs is provided.
1366
-
1367
- ### \`defaultPendingMinMs\` property
1368
-
1369
- - Type: \`number\`
1370
- - Optional
1371
- - Defaults to \`500\`
1372
- - The default \`pendingMinMs\` a route should use if no pendingMinMs is provided.
1373
-
1374
- ### \`defaultStaleTime\` property
1375
-
1376
- - Type: \`number\`
1377
- - Optional
1378
- - Defaults to \`0\`
1379
- - The default \`staleTime\` a route should use if no staleTime is provided.
1380
-
1381
- ### \`defaultPreloadStaleTime\` property
1382
-
1383
- - Type: \`number\`
1384
- - Optional
1385
- - Defaults to \`30_000\` ms (30 seconds)
1386
- - The default \`preloadStaleTime\` a route should use if no preloadStaleTime is provided.
1387
-
1388
- ### \`defaultPreloadGcTime\` property
1389
-
1390
- - Type: \`number\`
1391
- - Optional
1392
- - Defaults to \`routerOptions.defaultGcTime\`, which defaults to 30 minutes.
1393
- - The default \`preloadGcTime\` a route should use if no preloadGcTime is provided.
1394
-
1395
- ### \`defaultGcTime\` property
1396
-
1397
- - Type: \`number\`
1398
- - Optional
1399
- - Defaults to 30 minutes.
1400
- - The default \`gcTime\` a route should use if no gcTime is provided.
1401
-
1402
- ### \`defaultOnCatch\` property
1403
-
1404
- - Type: \`(error: Error, errorInfo: ErrorInfo) => void\`
1405
- - Optional
1406
- - The default \`onCatch\` handler for errors caught by the Router ErrorBoundary
1407
-
1408
- ### \`defaultViewTransition\` property
1409
-
1410
- - Type: \`boolean | ViewTransitionOptions\`
1411
- - Optional
1412
- - If \`true\`, route navigations will be called using \`document.startViewTransition()\`.
1413
- - If [\`ViewTransitionOptions\`](../ViewTransitionOptionsType.md), route navigations will be called using \`document.startViewTransition({update, types})\`
1414
- where \`types\` will be the strings array passed with \`ViewTransitionOptions["types"]\`. If the browser does not support viewTransition types,
1415
- the navigation will fall back to normal \`document.startTransition()\`, same as if \`true\` was passed.
1416
- - If the browser does not support this api, this option will be ignored.
1417
- - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
1418
- - See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types
1419
-
1420
- ### \`defaultHashScrollIntoView\` property
1421
-
1422
- - Type: \`boolean | ScrollIntoViewOptions\`
1423
- - Optional
1424
- - Defaults to \`true\` so the element with an id matching the hash will be scrolled into view after the location is committed to history.
1425
- - If \`false\`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.
1426
- - If an object is provided, it will be passed to the \`scrollIntoView\` method as options.
1427
- - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on \`ScrollIntoViewOptions\`.
1428
-
1429
- ### \`caseSensitive\` property
1430
-
1431
- - Type: \`boolean\`
1432
- - Optional
1433
- - Defaults to \`false\`
1434
- - If \`true\`, all routes will be matched as case-sensitive.
1435
-
1436
- ### \`basepath\` property
1437
-
1438
- - Type: \`string\`
1439
- - Optional
1440
- - Defaults to \`/\`
1441
- - The basepath for then entire router. This is useful for mounting a router instance at a subpath.
1442
-
1443
- ### \`context\` property
1444
-
1445
- - Type: \`any\`
1446
- - Optional or required if the root route was created with [\`createRootRouteWithContext()\`](../createRootRouteWithContextFunction.md).
1447
- - The root context that will be provided to all routes in the route tree. This can be used to provide a context to all routes in the tree without having to provide it to each route individually.
1448
-
1449
- ### \`dehydrate\` method
1450
-
1451
- - Type: \`() => TDehydrated\`
1452
- - Optional
1453
- - A function that will be called when the router is dehydrated. The return value of this function will be serialized and stored in the router's dehydrated state.
1454
-
1455
- ### \`hydrate\` method
1456
-
1457
- - Type: \`(dehydrated: TDehydrated) => void\`
1458
- - Optional
1459
- - A function that will be called when the router is hydrated. The return value of this function will be serialized and stored in the router's dehydrated state.
1460
-
1461
- ### \`routeMasks\` property
1462
-
1463
- - Type: \`RouteMask[]\`
1464
- - Optional
1465
- - An array of route masks that will be used to mask routes in the route tree. Route masking is when you display a route at a different path than the one it is configured to match, like a modal popup that when shared will unmask to the modal's content instead of the modal's context.
1466
-
1467
- ### \`unmaskOnReload\` property
1468
-
1469
- - Type: \`boolean\`
1470
- - Optional
1471
- - Defaults to \`false\`
1472
- - If \`true\`, route masks will, by default, be removed when the page is reloaded. This can be overridden on a per-mask basis by setting the \`unmaskOnReload\` option on the mask, or on a per-navigation basis by setting the \`unmaskOnReload\` option in the \`Navigate\` options.
1473
-
1474
- ### \`Wrap\` property
1475
-
1476
- - Type: \`React.Component\`
1477
- - Optional
1478
- - A component that will be used to wrap the entire router. This is useful for providing a context to the entire router. Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
1479
-
1480
- **Example**
1481
-
1482
- \`\`\`tsx
1483
- import { createRouter } from '@tanstack/react-router'
1484
-
1485
- const router = createRouter({
1486
- // ...
1487
- Wrap: ({ children }) => {
1488
- return <MyContext.Provider value={myContext}>{children}</MyContext>
1489
- },
1490
- })
1491
- \`\`\`
1492
-
1493
- ### \`InnerWrap\` property
1494
-
1495
- - Type: \`React.Component\`
1496
- - Optional
1497
- - A component that will be used to wrap the inner contents of the router. This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks. Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
1498
-
1499
- **Example**
1500
-
1501
- \`\`\`tsx
1502
- import { createRouter } from '@tanstack/react-router'
1503
-
1504
- const router = createRouter({
1505
- // ...
1506
- InnerWrap: ({ children }) => {
1507
- const routerState = useRouterState()
1508
-
1509
- return (
1510
- <MyContext.Provider value={myContext}>
1511
- {children}
1512
- </MyContext>
1513
- )
1514
- },
1515
- })
1516
- \`\`\`
1517
-
1518
- ### \`notFoundMode\` property
1519
-
1520
- - Type: \`'root' | 'fuzzy'\`
1521
- - Optional
1522
- - Defaults to \`'fuzzy'\`
1523
- - This property controls how TanStack Router will handle scenarios where it cannot find a route to match the current location. See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.
1524
-
1525
- ### \`notFoundRoute\` property
1526
-
1527
- - **Deprecated**
1528
- - Type: \`NotFoundRoute\`
1529
- - Optional
1530
- - A route that will be used as the default not found route for every branch of the route tree. This can be overridden on a per-branch basis by providing a not found route to the \`NotFoundRoute\` option on the root route of the branch.
1531
-
1532
- ### \`errorSerializer\` property
1533
-
1534
- - Type: [\`RouterErrorSerializer\`]
1535
- - Optional
1536
- - The serializer object that will be used to determine how errors are serialized and deserialized between the server and the client.
1537
-
1538
- #### \`errorSerializer.serialize\` method
1539
-
1540
- - Type: \`(err: unknown) => TSerializedError\`
1541
- - This method is called to define how errors are serialized when they are stored in the router's dehydrated state.
1542
-
1543
- #### \`errorSerializer.deserialize\` method
1544
-
1545
- - Type: \`(err: TSerializedError) => unknown\`
1546
- - This method is called to define how errors are deserialized from the router's dehydrated state.
1547
-
1548
- ### \`trailingSlash\` property
1549
-
1550
- - Type: \`'always' | 'never' | 'preserve'\`
1551
- - Optional
1552
- - Defaults to \`never\`
1553
- - Configures how trailing slashes are treated. \`'always'\` will add a trailing slash if not present, \`'never'\` will remove the trailing slash if present and \`'preserve'\` will not modify the trailing slash.
1554
-
1555
- ### \`pathParamsAllowedCharacters\` property
1556
-
1557
- - Type: \`Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>\`
1558
- - Optional
1559
- - Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.
1560
-
1561
- ### \`defaultStructuralSharing\` property
1562
-
1563
- - Type: \`boolean\`
1564
- - Optional
1565
- - Defaults to \`false\`
1566
- - Configures whether structural sharing is enabled by default for fine-grained selectors.
1567
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
1568
-
1569
- ### \`defaultRemountDeps\` property
1570
-
1571
- - Type:
1572
-
1573
- \`\`\`tsx
1574
- type defaultRemountDeps = (opts: RemountDepsOptions) => any
1575
-
1576
- interface RemountDepsOptions<
1577
- in out TRouteId,
1578
- in out TFullSearchSchema,
1579
- in out TAllParams,
1580
- in out TLoaderDeps,
1581
- > {
1582
- routeId: TRouteId
1583
- search: TFullSearchSchema
1584
- params: TAllParams
1585
- loaderDeps: TLoaderDeps
1586
- }
1587
- \`\`\`
1588
-
1589
- - Optional
1590
- - A default function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.
1591
- - The return value needs to be JSON serializable.
1592
- - By default, a route component will not be remounted if it stays active after a navigation
1593
-
1594
- Example:
1595
- If you want to configure to remount all route components upon \`params\` change, use:
1596
-
1597
- \`\`\`tsx
1598
- remountDeps: ({ params }) => params
1599
- \`\`\`
1600
-
1601
- # RouterState type
1602
-
1603
- The \`RouterState\` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc.
1604
-
1605
- \`\`\`tsx
1606
- type RouterState = {
1607
- status: 'pending' | 'idle'
1608
- isLoading: boolean
1609
- isTransitioning: boolean
1610
- matches: Array<RouteMatch>
1611
- pendingMatches: Array<RouteMatch>
1612
- location: ParsedLocation
1613
- resolvedLocation: ParsedLocation
1614
- }
1615
- \`\`\`
1616
-
1617
- ## RouterState properties
1618
-
1619
- The \`RouterState\` type contains all of the properties that are available on the router state.
1620
-
1621
- ### \`status\` property
1622
-
1623
- - Type: \`'pending' | 'idle'\`
1624
- - The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route.
1625
-
1626
- ### \`isLoading\` property
1627
-
1628
- - Type: \`boolean\`
1629
- - \`true\` if the router is currently loading a route or waiting for a route to finish loading.
1630
-
1631
- ### \`isTransitioning\` property
1632
-
1633
- - Type: \`boolean\`
1634
- - \`true\` if the router is currently transitioning to a new route.
1635
-
1636
- ### \`matches\` property
1637
-
1638
- - Type: [\`Array<RouteMatch>\`](../RouteMatchType.md)
1639
- - An array of all of the route matches that have been resolved and are currently active.
1640
-
1641
- ### \`pendingMatches\` property
1642
-
1643
- - Type: [\`Array<RouteMatch>\`](../RouteMatchType.md)
1644
- - An array of all of the route matches that are currently pending.
1645
-
1646
- ### \`location\` property
1647
-
1648
- - Type: [\`ParsedLocation\`](../ParsedLocationType.md)
1649
- - The latest location that the router has parsed from the browser history. This location may not be resolved and loaded yet.
1650
-
1651
- ### \`resolvedLocation\` property
1652
-
1653
- - Type: [\`ParsedLocation\`](../ParsedLocationType.md)
1654
- - The location that the router has resolved and loaded.
1655
-
1656
- # Router type
1657
-
1658
- The \`Router\` type is used to describe a router instance.
1659
-
1660
- ## \`Router\` properties and methods
1661
-
1662
- An instance of the \`Router\` has the following properties and methods:
1663
-
1664
- ### \`.update\` method
1665
-
1666
- - Type: \`(newOptions: RouterOptions) => void\`
1667
- - Updates the router instance with new options.
1668
-
1669
- ### \`state\` property
1670
-
1671
- - Type: [\`RouterState\`](../RouterStateType.md)
1672
- - The current state of the router.
1673
-
1674
- > ⚠️⚠️⚠️ **\`router.state\` is always up to date, but NOT REACTIVE. If you use \`router.state\` in a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use the [\`useRouterState\`](../useRouterStateHook.md) hook.**
1675
-
1676
- ### \`.subscribe\` method
1677
-
1678
- - Type: \`(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => (event: RouterEvent) => void\`
1679
- - Subscribes to a [\`RouterEvent\`](../RouterEventsType.md).
1680
- - Returns a function that can be used to unsubscribe from the event.
1681
- - The callback provided to the returned function will be called with the event that was emitted.
1682
-
1683
- ### \`.matchRoutes\` method
1684
-
1685
- - Type: \`(pathname: string, locationSearch: Record<string, any>, opts?: { throwOnError?: boolean; }) => RouteMatch[]\`
1686
- - Matches a pathname and search params against the router's route tree and returns an array of route matches.
1687
- - If \`opts.throwOnError\` is \`true\`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's \`error\` property).
1688
-
1689
- ### \`.cancelMatch\` method
1690
-
1691
- - Type: \`(matchId: string) => void\`
1692
- - Cancels a route match that is currently pending by calling \`match.abortController.abort()\`.
1693
-
1694
- ### \`.cancelMatches\` method
1695
-
1696
- - Type: \`() => void\`
1697
- - Cancels all route matches that are currently pending by calling \`match.abortController.abort()\` on each one.
1698
-
1699
- ### \`.buildLocation\` method
1700
-
1701
- Builds a new parsed location object that can be used later to navigate to a new location.
1702
-
1703
- - Type: \`(opts: BuildNextOptions) => ParsedLocation\`
1704
- - Properties
1705
- - \`from\`
1706
- - Type: \`string\`
1707
- - Optional
1708
- - The path to navigate from. If not provided, the current path will be used.
1709
- - \`to\`
1710
- - Type: \`string | number | null\`
1711
- - Optional
1712
- - The path to navigate to. If \`null\`, the current path will be used.
1713
- - \`params\`
1714
- - Type: \`true | Updater<unknown>\`
1715
- - Optional
1716
- - If \`true\`, the current params will be used. If a function is provided, it will be called with the current params and the return value will be used.
1717
- - \`search\`
1718
- - Type: \`true | Updater<unknown>\`
1719
- - Optional
1720
- - If \`true\`, the current search params will be used. If a function is provided, it will be called with the current search params and the return value will be used.
1721
- - \`hash\`
1722
- - Type: \`true | Updater<string>\`
1723
- - Optional
1724
- - If \`true\`, the current hash will be used. If a function is provided, it will be called with the current hash and the return value will be used.
1725
- - \`state\`
1726
- - Type: \`true | NonNullableUpdater<ParsedHistoryState, HistoryState>\`
1727
- - Optional
1728
- - If \`true\`, the current state will be used. If a function is provided, it will be called with the current state and the return value will be used.
1729
- - \`mask\`
1730
- - Type: \`object\`
1731
- - Optional
1732
- - Contains all of the same BuildNextOptions, with the addition of \`unmaskOnReload\`.
1733
- - \`unmaskOnReload\`
1734
- - Type: \`boolean\`
1735
- - Optional
1736
- - If \`true\`, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting the \`unmaskOnReload\` option in the \`Navigate\` options.
1737
-
1738
- ### \`.commitLocation\` method
1739
-
1740
- Commits a new location object to the browser history.
1741
-
1742
- - Type
1743
- \`\`\`tsx
1744
- type commitLocation = (
1745
- location: ParsedLocation & {
1746
- replace?: boolean
1747
- resetScroll?: boolean
1748
- hashScrollIntoView?: boolean | ScrollIntoViewOptions
1749
- ignoreBlocker?: boolean
1750
- },
1751
- ) => Promise<void>
1752
- \`\`\`
1753
- - Properties
1754
- - \`location\`
1755
- - Type: [\`ParsedLocation\`](../ParsedLocationType.md)
1756
- - Required
1757
- - The location to commit to the browser history.
1758
- - \`replace\`
1759
- - Type: \`boolean\`
1760
- - Optional
1761
- - Defaults to \`false\`.
1762
- - If \`true\`, the location will be committed to the browser history using \`history.replace\` instead of \`history.push\`.
1763
- - \`resetScroll\`
1764
- - Type: \`boolean\`
1765
- - Optional
1766
- - Defaults to \`true\` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.
1767
- - If \`false\`, the scroll position will not be reset to 0,0 after the location is committed to history.
1768
- - \`hashScrollIntoView\`
1769
- - Type: \`boolean | ScrollIntoViewOptions\`
1770
- - Optional
1771
- - Defaults to \`true\` so the element with an id matching the hash will be scrolled into view after the location is committed to history.
1772
- - If \`false\`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.
1773
- - If an object is provided, it will be passed to the \`scrollIntoView\` method as options.
1774
- - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on \`ScrollIntoViewOptions\`.
1775
- - \`ignoreBlocker\`
1776
- - Type: \`boolean\`
1777
- - Optional
1778
- - Defaults to \`false\`.
1779
- - If \`true\`, navigation will ignore any blockers that might prevent it.
1780
-
1781
- ### \`.navigate\` method
1782
-
1783
- Navigates to a new location.
1784
-
1785
- - Type
1786
- \`\`\`tsx
1787
- type navigate = (options: NavigateOptions) => Promise<void>
1788
- \`\`\`
1789
-
1790
- ### \`.invalidate\` method
1791
-
1792
- Invalidates route matches by forcing their \`beforeLoad\` and \`load\` functions to be called again.
1793
-
1794
- - Type: \`(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean, sync?: boolean}) => Promise<void>\`
1795
- - This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date.
1796
- - if \`filter\` is not supplied, all matches will be invalidated
1797
- - if \`filter\` is supplied, only matches for which \`filter\` returns \`true\` will be invalidated.
1798
- - if \`sync\` is true, the promise returned by this function will only resolve once all loaders have finished.
1799
- - You might also want to invalidate the Router if you imperatively \`reset\` the router's \`CatchBoundary\` to trigger loaders again.
1800
-
1801
- ### \`.clearCache\` method
1802
-
1803
- Remove cached route matches.
1804
-
1805
- - Type: \`(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean}) => void\`
1806
- - if \`filter\` is not supplied, all cached matches will be removed
1807
- - if \`filter\` is supplied, only matches for which \`filter\` returns \`true\` will be removed.
1808
-
1809
- ### \`.load\` method
1810
-
1811
- Loads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered.
1812
-
1813
- > ⚠️⚠️⚠️ **\`router.load()\` respects \`route.staleTime\` and will not forcefully reload a route match if it is still fresh. If you need to forcefully reload a route match, use \`router.invalidate()\` instead.**
1814
-
1815
- - Type: \`(opts?: {sync?: boolean}) => Promise<void>\`
1816
- - if \`sync\` is true, the promise returned by this function will only resolve once all loaders have finished.
1817
- - The most common use case for this method is to call it when doing SSR to ensure that all of the critical data for the current route is loaded before attempting to stream or render the application to the client.
1818
-
1819
- ### \`.preloadRoute\` method
1820
-
1821
- Preloads all of the matches that match the provided \`NavigateOptions\`.
1822
-
1823
- > ⚠️⚠️⚠️ **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.**
1824
-
1825
- - Type: \`(opts?: NavigateOptions) => Promise<RouteMatch[]>\`
1826
- - Properties
1827
- - \`opts\`
1828
- - Type: \`NavigateOptions\`
1829
- - Optional, defaults to the current location.
1830
- - The options that will be used to determine which route matches to preload.
1831
- - Returns
1832
- - A promise that resolves with an array of all of the route matches that were preloaded.
1833
-
1834
- ### \`.loadRouteChunk\` method
1835
-
1836
- Loads the JS chunk of the route.
1837
-
1838
- - Type: \`(route: AnyRoute) => Promise<void>\`
1839
-
1840
- ### \`.matchRoute\` method
1841
-
1842
- Matches a pathname and search params against the router's route tree and returns a route match's params or false if no match was found.
1843
-
1844
- - Type: \`(dest: ToOptions, matchOpts?: MatchRouteOptions) => RouteMatch['params'] | false\`
1845
- - Properties
1846
- - \`dest\`
1847
- - Type: \`ToOptions\`
1848
- - Required
1849
- - The destination to match against.
1850
- - \`matchOpts\`
1851
- - Type: \`MatchRouteOptions\`
1852
- - Optional
1853
- - Options that will be used to match the destination.
1854
- - Returns
1855
- - A route match's params if a match was found.
1856
- - \`false\` if no match was found.
1857
-
1858
- ### \`.dehydrate\` method
1859
-
1860
- Dehydrates the router's critical state into a serializable object that can be sent to the client in an initial request.
1861
-
1862
- - Type: \`() => DehydratedRouter\`
1863
- - Returns
1864
- - A serializable object that contains the router's critical state.
1865
-
1866
- ### \`.hydrate\` method
1867
-
1868
- Hydrates the router's critical state from a serializable object that was sent from the server in an initial request.
1869
-
1870
- - Type: \`(dehydrated: DehydratedRouter) => void\`
1871
- - Properties
1872
- - \`dehydrated\`
1873
- - Type: \`DehydratedRouter\`
1874
- - Required
1875
- - The dehydrated router state that was sent from the server.
1876
-
1877
- # ToMaskOptions type
1878
-
1879
- The \`ToMaskOptions\` type extends the [\`ToOptions\`](../ToOptionsType.md) type and describes additional options available when using route masks.
1880
-
1881
- \`\`\`tsx
1882
- type ToMaskOptions = ToOptions & {
1883
- unmaskOnReload?: boolean
1884
- }
1885
- \`\`\`
1886
-
1887
- - [\`ToOptions\`](../ToOptionsType.md)
1888
-
1889
- # ToOptions type
1890
-
1891
- The \`ToOptions\` type contains several properties that can be used to describe a router destination.
1892
-
1893
- \`\`\`tsx
1894
- type ToOptions = {
1895
- from?: ValidRoutePath | string
1896
- to?: ValidRoutePath | string
1897
- hash?: true | string | ((prev?: string) => string)
1898
- state?: true | HistoryState | ((prev: HistoryState) => HistoryState)
1899
- } & SearchParamOptions &
1900
- PathParamOptions
1901
-
1902
- type SearchParamOptions = {
1903
- search?: true | TToSearch | ((prev: TFromSearch) => TToSearch)
1904
- }
1905
-
1906
- type PathParamOptions = {
1907
- path?: true | Record<string, TPathParam> | ((prev: TFromParams) => TToParams)
1908
- }
1909
- \`\`\`
1910
-
1911
- # UseMatchRouteOptions type
1912
-
1913
- The \`UseMatchRouteOptions\` type extends the [\`ToOptions\`](../ToOptionsType.md) type and describes additional options available when using the [\`useMatchRoute\`](../useMatchRouteHook.md) hook.
1914
-
1915
- \`\`\`tsx
1916
- export type UseMatchRouteOptions = ToOptions & MatchRouteOptions
1917
- \`\`\`
1918
-
1919
- - [\`ToOptions\`](../ToOptionsType.md)
1920
- - [\`MatchRouteOptions\`](../MatchRouteOptionsType.md)
1921
-
1922
- # ViewTransitionOptions type
1923
-
1924
- The \`ViewTransitionOptions\` type is used to define a
1925
- [viewTransition type](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types).
1926
-
1927
- \`\`\`tsx
1928
- interface ViewTransitionOptions {
1929
- types: Array<string>
1930
- }
1931
- \`\`\`
1932
-
1933
- ## ViewTransitionOptions properties
1934
-
1935
- The \`ViewTransitionOptions\` type accepts an object with a single property:
1936
-
1937
- ### \`types\` property
1938
-
1939
- - Type: \`Array<string>\`
1940
- - Required
1941
- - The types array that will be passed to the \`document.startViewTransition({update, types}) call\`;
1942
-
1943
- # Await component
1944
-
1945
- The \`Await\` component is a component that suspends until the provided promise is resolved or rejected.
1946
- This is only necessary for React 18.
1947
- If you are using React 19, you can use the \`use()\` hook instead.
1948
-
1949
- ## Await props
1950
-
1951
- The \`Await\` component accepts the following props:
1952
-
1953
- ### \`props.promise\` prop
1954
-
1955
- - Type: \`Promise<T>\`
1956
- - Required
1957
- - The promise to await.
1958
-
1959
- ### \`props.children\` prop
1960
-
1961
- - Type: \`(result: T) => React.ReactNode\`
1962
- - Required
1963
- - A function that will be called with the resolved value of the promise.
1964
-
1965
- ## Await returns
1966
-
1967
- - Throws an error if the promise is rejected.
1968
- - Suspends (throws a promise) if the promise is pending.
1969
- - Returns the resolved value of a deferred promise if the promise is resolved using \`props.children\` as the render function.
1970
-
1971
- ## Examples
1972
-
1973
- \`\`\`tsx
1974
- import { Await } from '@tanstack/react-router'
1975
-
1976
- function Component() {
1977
- const { deferredPromise } = route.useLoaderData()
1978
-
1979
- return (
1980
- <Await promise={deferredPromise}>
1981
- {(data) => <div>{JSON.stringify(data)}</div>}
1982
- </Await>
1983
- )
1984
- }
1985
- \`\`\`
1986
-
1987
- # CatchBoundary component
1988
-
1989
- The \`CatchBoundary\` component is a component that catches errors thrown by its children, renders an error component and optionally calls the \`onCatch\` callback. It also accepts a \`getResetKey\` function that can be used to declaratively reset the component's state when the key changes.
1990
-
1991
- ## CatchBoundary props
1992
-
1993
- The \`CatchBoundary\` component accepts the following props:
1994
-
1995
- ### \`props.getResetKey\` prop
1996
-
1997
- - Type: \`() => string\`
1998
- - Required
1999
- - A function that returns a string that will be used to reset the component's state when the key changes.
2000
-
2001
- ### \`props.children\` prop
2002
-
2003
- - Type: \`React.ReactNode\`
2004
- - Required
2005
- - The component's children to render when there is no error
2006
-
2007
- ### \`props.errorComponent\` prop
2008
-
2009
- - Type: \`React.ReactNode\`
2010
- - Optional - [\`default: ErrorComponent\`](../errorComponentComponent.md)
2011
- - The component to render when there is an error.
2012
-
2013
- ### \`props.onCatch\` prop
2014
-
2015
- - Type: \`(error: any) => void\`
2016
- - Optional
2017
- - A callback that will be called with the error that was thrown by the component's children.
2018
-
2019
- ## CatchBoundary returns
2020
-
2021
- - Returns the component's children if there is no error.
2022
- - Returns the \`errorComponent\` if there is an error.
2023
-
2024
- ## Examples
2025
-
2026
- \`\`\`tsx
2027
- import { CatchBoundary } from '@tanstack/react-router'
2028
-
2029
- function Component() {
2030
- return (
2031
- <CatchBoundary
2032
- getResetKey={() => 'reset'}
2033
- onCatch={(error) => console.error(error)}
2034
- >
2035
- <div>My Component</div>
2036
- </CatchBoundary>
2037
- )
2038
- }
2039
- \`\`\`
2040
-
2041
- # CatchNotFound Component
2042
-
2043
- The \`CatchNotFound\` component is a component that catches not-found errors thrown by its children, renders a fallback component and optionally calls the \`onCatch\` callback. It resets when the pathname changes.
2044
-
2045
- ## CatchNotFound props
2046
-
2047
- The \`CatchNotFound\` component accepts the following props:
2048
-
2049
- ### \`props.children\` prop
2050
-
2051
- - Type: \`React.ReactNode\`
2052
- - Required
2053
- - The component's children to render when there is no error
2054
-
2055
- ### \`props.fallback\` prop
2056
-
2057
- - Type: \`(error: NotFoundError) => React.ReactElement\`
2058
- - Optional
2059
- - The component to render when there is an error
2060
-
2061
- ### \`props.onCatch\` prop
2062
-
2063
- - Type: \`(error: any) => void\`
2064
- - Optional
2065
- - A callback that will be called with the error that was thrown by the component's children
2066
-
2067
- ## CatchNotFound returns
2068
-
2069
- - Returns the component's children if there is no error.
2070
- - Returns the \`fallback\` if there is an error.
2071
-
2072
- ## Examples
2073
-
2074
- \`\`\`tsx
2075
- import { CatchNotFound } from '@tanstack/react-router'
2076
-
2077
- function Component() {
2078
- return (
2079
- <CatchNotFound
2080
- fallback={(error) => <p>Not found error! {JSON.stringify(error)}</p>}
2081
- >
2082
- <ComponentThatMightThrowANotFoundError />
2083
- </CatchNotFound>
2084
- )
2085
- }
2086
- \`\`\`
2087
-
2088
- # ClientOnly Component
2089
-
2090
- The \`ClientOnly\` component is used to render a components only in the client, without breaking the server-side rendering due to hydration errors. It accepts a \`fallback\` prop that will be rendered if the JS is not yet loaded in the client.
2091
-
2092
- ## Props
2093
-
2094
- The \`ClientOnly\` component accepts the following props:
2095
-
2096
- ### \`props.fallback\` prop
2097
-
2098
- The fallback component to render if the JS is not yet loaded in the client.
2099
-
2100
- ### \`props.children\` prop
2101
-
2102
- The component to render if the JS is loaded in the client.
2103
-
2104
- ## Returns
2105
-
2106
- - Returns the component's children if the JS is loaded in the client.
2107
- - Returns the \`fallback\` component if the JS is not yet loaded in the client.
2108
-
2109
- ## Examples
2110
-
2111
- \`\`\`tsx
2112
- // src/routes/dashboard.tsx
2113
- import { ClientOnly, createFileRoute } from '@tanstack/react-router'
2114
- import {
2115
- Charts,
2116
- FallbackCharts,
2117
- } from './charts-that-break-server-side-rendering'
2118
-
2119
- export const Route = createFileRoute('/dashboard')({
2120
- component: Dashboard,
2121
- // ... other route options
2122
- })
2123
-
2124
- function Dashboard() {
2125
- return (
2126
- <div>
2127
- <p>Dashboard</p>
2128
- <ClientOnly fallback={<FallbackCharts />}>
2129
- <Charts />
2130
- </ClientOnly>
2131
- </div>
2132
- )
2133
- }
2134
- \`\`\`
2135
-
2136
- # createFileRoute function
2137
-
2138
- The \`createFileRoute\` function is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the \`tsr generate\` and \`tsr watch\` commands.
2139
-
2140
- ## createFileRoute options
2141
-
2142
- The \`createFileRoute\` function accepts a single argument of type \`string\` that represents the \`path\` of the file that the route will be generated from.
2143
-
2144
- ### \`path\` option
2145
-
2146
- - Type: \`string\` literal
2147
- - Required, but **automatically inserted and updated by the \`tsr generate\` and \`tsr watch\` commands**
2148
- - The full path of the file that the route will be generated from
2149
-
2150
- ## createFileRoute returns
2151
-
2152
- A new function that accepts a single argument of type [\`RouteOptions\`](../RouteOptionsType.md) that will be used to configure the file [\`Route\`](../RouteType.md) instance.
2153
-
2154
- > ⚠️ Note: For \`tsr generate\` and \`tsr watch\` to work properly, the file route instance must be exported from the file using the \`Route\` identifier.
2155
-
2156
- ## Examples
2157
-
2158
- \`\`\`tsx
2159
- import { createFileRoute } from '@tanstack/react-router'
2160
-
2161
- export const Route = createFileRoute({
2162
- loader: () => {
2163
- return 'Hello World'
2164
- },
2165
- component: IndexComponent,
2166
- })
2167
-
2168
- function IndexComponent() {
2169
- const data = Route.useLoaderData()
2170
- return <div>{data}</div>
2171
- }
2172
- \`\`\`
2173
-
2174
- # createLazyFileRoute function
2175
-
2176
- The \`createLazyFileRoute\` function is used for creating a partial file-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as \`component\`, \`pendingComponent\`, \`errorComponent\`, and the \`notFoundComponent\`.
2177
-
2178
- ## createLazyFileRoute options
2179
-
2180
- The \`createLazyFileRoute\` function accepts a single argument of type \`string\` that represents the \`path\` of the file that the route will be generated from.
2181
-
2182
- ### \`path\`
2183
-
2184
- - Type: \`string\`
2185
- - Required, but **automatically inserted and updated by the \`tsr generate\` and \`tsr watch\` commands**
2186
- - The full path of the file that the route will be generated from.
2187
-
2188
- ### createLazyFileRoute returns
2189
-
2190
- A new function that accepts a single argument of partial of the type [\`RouteOptions\`](../RouteOptionsType.md) that will be used to configure the file [\`Route\`](../RouteType.md) instance.
2191
-
2192
- - Type:
2193
-
2194
- \`\`\`tsx
2195
- Pick<
2196
- RouteOptions,
2197
- 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'
2198
- >
2199
- \`\`\`
2200
-
2201
- - [\`RouteOptions\`](../RouteOptionsType.md)
2202
-
2203
- > ⚠️ Note: For \`tsr generate\` and \`tsr watch\` to work properly, the file route instance must be exported from the file using the \`Route\` identifier.
2204
-
2205
- ### Examples
2206
-
2207
- \`\`\`tsx
2208
- import { createLazyFileRoute } from '@tanstack/react-router'
2209
-
2210
- export const Route = createLazyFileRoute('/')({
2211
- component: IndexComponent,
2212
- })
2213
-
2214
- function IndexComponent() {
2215
- const data = Route.useLoaderData()
2216
- return <div>{data}</div>
2217
- }
2218
- \`\`\`
2219
-
2220
- # createLazyRoute function
2221
-
2222
- The \`createLazyRoute\` function is used for creating a partial code-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as \`component\`, \`pendingComponent\`, \`errorComponent\`, and the \`notFoundComponent\`.
2223
-
2224
- ## createLazyRoute options
2225
-
2226
- The \`createLazyRoute\` function accepts a single argument of type \`string\` that represents the \`id\` of the route.
2227
-
2228
- ### \`id\`
2229
-
2230
- - Type: \`string\`
2231
- - Required
2232
- - The route id of the route.
2233
-
2234
- ### createLazyRoute returns
2235
-
2236
- A new function that accepts a single argument of partial of the type [\`RouteOptions\`](../RouteOptionsType.md) that will be used to configure the file [\`Route\`](../RouteType.md) instance.
2237
-
2238
- - Type:
2239
-
2240
- \`\`\`tsx
2241
- Pick<
2242
- RouteOptions,
2243
- 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'
2244
- >
2245
- \`\`\`
2246
-
2247
- - [\`RouteOptions\`](../RouteOptionsType.md)
2248
-
2249
- > ⚠️ Note: This route instance must be manually lazily loaded against its critical route instance using the \`lazy\` method returned by the \`createRoute\` function.
2250
-
2251
- ### Examples
2252
-
2253
- \`\`\`tsx
2254
- // src/route-pages/index.tsx
2255
- import { createLazyRoute } from '@tanstack/react-router'
2256
-
2257
- export const Route = createLazyRoute('/')({
2258
- component: IndexComponent,
2259
- })
2260
-
2261
- function IndexComponent() {
2262
- const data = Route.useLoaderData()
2263
- return <div>{data}</div>
2264
- }
2265
-
2266
- // src/routeTree.tsx
2267
- import {
2268
- createRootRouteWithContext,
2269
- createRoute,
2270
- Outlet,
2271
- } from '@tanstack/react-router'
2272
-
2273
- interface MyRouterContext {
2274
- foo: string
2275
- }
2276
-
2277
- const rootRoute = createRootRouteWithContext<MyRouterContext>()({
2278
- component: () => <Outlet />,
2279
- })
2280
-
2281
- const indexRoute = createRoute({
2282
- getParentRoute: () => rootRoute,
2283
- path: '/',
2284
- }).lazy(() => import('./route-pages/index').then((d) => d.Route))
2285
-
2286
- export const routeTree = rootRoute.addChildren([indexRoute])
2287
- \`\`\`
2288
-
2289
- # createRootRoute function
2290
-
2291
- The \`createRootRoute\` function returns a new root route instance. A root route instance can then be used to create a route-tree.
2292
-
2293
- ## createRootRoute options
2294
-
2295
- The options that will be used to configure the root route instance.
2296
-
2297
- - Type:
2298
-
2299
- \`\`\`tsx
2300
- Omit<
2301
- RouteOptions,
2302
- | 'path'
2303
- | 'id'
2304
- | 'getParentRoute'
2305
- | 'caseSensitive'
2306
- | 'parseParams'
2307
- | 'stringifyParams'
2308
- >
2309
- \`\`\`
2310
-
2311
- - [\`RouteOptions\`](../RouteOptionsType.md)
2312
- - Optional
2313
-
2314
- ## createRootRoute returns
2315
-
2316
- A new [\`Route\`](../RouteType.md) instance.
2317
-
2318
- ## Examples
2319
-
2320
- \`\`\`tsx
2321
- import { createRootRoute, createRouter, Outlet } from '@tanstack/react-router'
2322
-
2323
- const rootRoute = createRootRoute({
2324
- component: () => <Outlet />,
2325
- // ... root route options
2326
- })
2327
-
2328
- const routeTree = rootRoute.addChildren([
2329
- // ... other routes
2330
- ])
2331
-
2332
- const router = createRouter({
2333
- routeTree,
2334
- })
2335
- \`\`\`
2336
-
2337
- # createRootRouteWithContext function
2338
-
2339
- The \`createRootRouteWithContext\` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created.
2340
-
2341
- ## createRootRouteWithContext generics
2342
-
2343
- The \`createRootRouteWithContext\` function accepts a single generic argument:
2344
-
2345
- ### \`TRouterContext\` generic
2346
-
2347
- - Type: \`TRouterContext\`
2348
- - Optional, **but recommended**.
2349
- - The context type that will be required to be fulfilled when the router is created
2350
-
2351
- ## createRootRouteWithContext returns
2352
-
2353
- - A factory function that can be used to create a new [\`createRootRoute\`](../createRootRouteFunction.md) instance.
2354
- - It accepts a single argument, the same as the [\`createRootRoute\`](../createRootRouteFunction.md) function.
2355
-
2356
- ## Examples
2357
-
2358
- \`\`\`tsx
2359
- import {
2360
- createRootRouteWithContext,
2361
- createRouter,
2362
- } from '@tanstack/react-router'
2363
- import { QueryClient } from '@tanstack/react-query'
2364
-
2365
- interface MyRouterContext {
2366
- queryClient: QueryClient
2367
- }
2368
-
2369
- const rootRoute = createRootRouteWithContext<MyRouterContext>()({
2370
- component: () => <Outlet />,
2371
- // ... root route options
2372
- })
2373
-
2374
- const routeTree = rootRoute.addChildren([
2375
- // ... other routes
2376
- ])
2377
-
2378
- const queryClient = new QueryClient()
2379
-
2380
- const router = createRouter({
2381
- routeTree,
2382
- context: {
2383
- queryClient,
2384
- },
2385
- })
2386
- \`\`\`
2387
-
2388
- # createRoute function
2389
-
2390
- The \`createRoute\` function implements returns a [\`Route\`](../RouteType.md) instance. A route instance can then be passed to a root route's children to create a route tree, which is then passed to the router.
2391
-
2392
- ## createRoute options
2393
-
2394
- - Type: [\`RouteOptions\`](../RouteOptionsType.md)
2395
- - Required
2396
- - The options that will be used to configure the route instance
2397
-
2398
- ## createRoute returns
2399
-
2400
- A new [\`Route\`](../RouteType.md) instance.
2401
-
2402
- ## Examples
2403
-
2404
- \`\`\`tsx
2405
- import { createRoute } from '@tanstack/react-router'
2406
- import { rootRoute } from './__root'
2407
-
2408
- const Route = createRoute({
2409
- getParentRoute: () => rootRoute,
2410
- path: '/',
2411
- loader: () => {
2412
- return 'Hello World'
2413
- },
2414
- component: IndexComponent,
2415
- })
2416
-
2417
- function IndexComponent() {
2418
- const data = Route.useLoaderData()
2419
- return <div>{data}</div>
2420
- }
2421
- \`\`\`
2422
-
2423
- # createRouteMask function
2424
-
2425
- The \`createRouteMask\` function is a helper function that can be used to create a route mask configuration that can be passed to the \`RouterOptions.routeMasks\` option.
2426
-
2427
- ## createRouteMask options
2428
-
2429
- - Type: [\`RouteMask\`](../RouteMaskType.md)
2430
- - Required
2431
- - The options that will be used to configure the route mask
2432
-
2433
- ## createRouteMask returns
2434
-
2435
- - A object with the type signature of [\`RouteMask\`](../RouteMaskType.md) that can be passed to the \`RouterOptions.routeMasks\` option.
2436
-
2437
- ## Examples
2438
-
2439
- \`\`\`tsx
2440
- import { createRouteMask, createRouter } from '@tanstack/react-router'
2441
-
2442
- const photoModalToPhotoMask = createRouteMask({
2443
- routeTree,
2444
- from: '/photos/$photoId/modal',
2445
- to: '/photos/$photoId',
2446
- params: true,
2447
- })
2448
-
2449
- // Set up a Router instance
2450
- const router = createRouter({
2451
- routeTree,
2452
- routeMasks: [photoModalToPhotoMask],
2453
- })
2454
- \`\`\`
2455
-
2456
- # createRouter function
2457
-
2458
- The \`createRouter\` function accepts a [\`RouterOptions\`](../RouterOptionsType.md) object and creates a new [\`Router\`](../RouterClass.md) instance.
2459
-
2460
- ## createRouter options
2461
-
2462
- - Type: [\`RouterOptions\`](../RouterOptionsType.md)
2463
- - Required
2464
- - The options that will be used to configure the router instance.
2465
-
2466
- ## createRouter returns
2467
-
2468
- - An instance of the [\`Router\`](../RouterType.md).
2469
-
2470
- ## Examples
2471
-
2472
- \`\`\`tsx
2473
- import { createRouter, RouterProvider } from '@tanstack/react-router'
2474
- import { routeTree } from './routeTree.gen'
2475
-
2476
- const router = createRouter({
2477
- routeTree,
2478
- defaultPreload: 'intent',
2479
- })
2480
-
2481
- export default function App() {
2482
- return <RouterProvider router={router} />
2483
- }
2484
- \`\`\`
2485
-
2486
- # DefaultGlobalNotFound component
2487
-
2488
- The \`DefaultGlobalNotFound\` component is a component that renders "Not Found" on the root route when there is no other route that matches and a \`notFoundComponent\` is not provided.
2489
-
2490
- ## DefaultGlobalNotFound returns
2491
-
2492
- \`\`\`tsx
2493
- <p>Not Found</p>
2494
- \`\`\`
2495
-
2496
- # defer function
2497
-
2498
- > [!CAUTION]
2499
- > You don't need to call \`defer\` manually anymore, Promises are handled automatically now.
2500
-
2501
- The \`defer\` function wraps a promise with a deferred state object that can be used to inspect the promise's state. This deferred promise can then be passed to the [\`useAwaited\`](../useAwaitedHook.md) hook or the [\`<Await>\`](../awaitComponent.md) component for suspending until the promise is resolved or rejected.
2502
-
2503
- The \`defer\` function accepts a single argument, the \`promise\` to wrap with a deferred state object.
2504
-
2505
- ## defer options
2506
-
2507
- - Type: \`Promise<T>\`
2508
- - Required
2509
- - The promise to wrap with a deferred state object.
2510
-
2511
- ## defer returns
2512
-
2513
- - A promise that can be passed to the [\`useAwaited\`](../useAwaitedHook.md) hook or the [\`<Await>\`](../awaitComponent.md) component.
2514
-
2515
- ## Examples
2516
-
2517
- \`\`\`tsx
2518
- import { defer } from '@tanstack/react-router'
2519
-
2520
- const route = createRoute({
2521
- loader: () => {
2522
- const deferredPromise = defer(fetch('/api/data'))
2523
- return { deferredPromise }
2524
- },
2525
- component: MyComponent,
2526
- })
2527
-
2528
- function MyComponent() {
2529
- const { deferredPromise } = Route.useLoaderData()
2530
-
2531
- const data = useAwaited({ promise: deferredPromise })
2532
-
2533
- // or
2534
-
2535
- return (
2536
- <Await promise={deferredPromise}>
2537
- {(data) => <div>{JSON.stringify(data)}</div>}
2538
- </Await>
2539
- )
2540
- }
2541
- \`\`\`
2542
-
2543
- # ErrorComponent component
2544
-
2545
- The \`ErrorComponent\` component is a component that renders an error message and optionally the error's message.
2546
-
2547
- ## ErrorComponent props
2548
-
2549
- The \`ErrorComponent\` component accepts the following props:
2550
-
2551
- ### \`props.error\` prop
2552
-
2553
- - Type: \`any\`
2554
- - The error that was thrown by the component's children
2555
-
2556
- ### \`props.reset\` prop
2557
-
2558
- - Type: \`() => void\`
2559
- - A function to programmatically reset the error state
2560
-
2561
- ## ErrorComponent returns
2562
-
2563
- - Returns a formatted error message with the error's message if it exists.
2564
- - The error message can be toggled by clicking the "Show Error" button.
2565
- - By default, the error message will be shown in development.
2566
-
2567
- # getRouteApi function
2568
-
2569
- The \`getRouteApi\` function provides type-safe version of common hooks like \`useParams\`, \`useSearch\`, \`useRouteContext\`, \`useNavigate\`, \`useLoaderData\`, and \`useLoaderDeps\` that are pre-bound to a specific route ID and corresponding registered route types.
2570
-
2571
- ## getRouteApi options
2572
-
2573
- The \`getRouteApi\` function accepts a single argument, a \`routeId\` string literal.
2574
-
2575
- ### \`routeId\` option
2576
-
2577
- - Type: \`string\`
2578
- - Required
2579
- - The route ID to which the [\`RouteApi\`](../RouteApiClass.md) instance will be bound
2580
-
2581
- ## getRouteApi returns
2582
-
2583
- - An instance of the [\`RouteApi\`](../RouteApiType.md) that is pre-bound to the route ID that the \`getRouteApi\` function was called with.
2584
-
2585
- ## Examples
2586
-
2587
- \`\`\`tsx
2588
- import { getRouteApi } from '@tanstack/react-router'
2589
-
2590
- const routeApi = getRouteApi('/posts')
2591
-
2592
- export function PostsPage() {
2593
- const posts = routeApi.useLoaderData()
2594
- // ...
2595
- }
2596
- \`\`\`
2597
-
2598
- # HistoryState interface
2599
-
2600
- The \`HistoryState\` interface is an interface exported by the \`history\` package that describes the shape of the state object that can be used in conjunction with the \`history\` package and the \`window.location\` API.
2601
-
2602
- You can extend this interface to add additional properties to the state object across your application.
2603
-
2604
- \`\`\`tsx
2605
- // src/main.tsx
2606
- declare module '@tanstack/react-router' {
2607
- // ...
2608
-
2609
- interface HistoryState {
2610
- additionalRequiredProperty: number
2611
- additionalProperty?: string
2612
- }
2613
- }
2614
- \`\`\`
2615
-
2616
- # isNotFound function
2617
-
2618
- The \`isNotFound\` function can be used to determine if an object is a [\`NotFoundError\`](../NotFoundErrorType.md) object.
2619
-
2620
- ## isNotFound options
2621
-
2622
- The \`isNotFound\` function accepts a single argument, an \`input\`.
2623
-
2624
- ### \`input\` option
2625
-
2626
- - Type: \`unknown\`
2627
- - Required
2628
- - An object to check if it is a [\`NotFoundError\`](../NotFoundErrorType.md).
2629
-
2630
- ## isNotFound returns
2631
-
2632
- - Type: \`boolean\`
2633
- - \`true\` if the object is a [\`NotFoundError\`](../NotFoundErrorType.md).
2634
- - \`false\` if the object is not a [\`NotFoundError\`](../NotFoundErrorType.md).
2635
-
2636
- ## Examples
2637
-
2638
- \`\`\`tsx
2639
- import { isNotFound } from '@tanstack/react-router'
2640
-
2641
- function somewhere(obj: unknown) {
2642
- if (isNotFound(obj)) {
2643
- // ...
2644
- }
2645
- }
2646
- \`\`\`
2647
-
2648
- # isRedirect function
2649
-
2650
- The \`isRedirect\` function can be used to determine if an object is a redirect object.
2651
-
2652
- ## isRedirect options
2653
-
2654
- The \`isRedirect\` function accepts a single argument, an \`input\`.
2655
-
2656
- #### \`input\`
2657
-
2658
- - Type: \`unknown\`
2659
- - Required
2660
- - An object to check if it is a redirect object
2661
-
2662
- ## isRedirect returns
2663
-
2664
- - Type: \`boolean\`
2665
- - \`true\` if the object is a redirect object
2666
- - \`false\` if the object is not a redirect object
2667
-
2668
- ## Examples
2669
-
2670
- \`\`\`tsx
2671
- import { isRedirect } from '@tanstack/react-router'
2672
-
2673
- function somewhere(obj: unknown) {
2674
- if (isRedirect(obj)) {
2675
- // ...
2676
- }
2677
- }
2678
- \`\`\`
2679
-
2680
- # lazyRouteComponent function
2681
-
2682
- > [!IMPORTANT]
2683
- > If you are using file-based routing, it's recommended to use the \`createLazyFileRoute\` function instead.
2684
-
2685
- The \`lazyRouteComponent\` function can be used to create a one-off code-split route component that can be preloaded using a \`component.preload()\` method.
2686
-
2687
- ## lazyRouteComponent options
2688
-
2689
- The \`lazyRouteComponent\` function accepts two arguments:
2690
-
2691
- ### \`importer\` option
2692
-
2693
- - Type: \`() => Promise<T>\`
2694
- - Required
2695
- - A function that returns a promise that resolves to an object that contains the component to be loaded.
2696
-
2697
- ### \`exportName\` option
2698
-
2699
- - Type: \`string\`
2700
- - Optional
2701
- - The name of the component to be loaded from the imported object. Defaults to \`'default'\`.
2702
-
2703
- ## lazyRouteComponent returns
2704
-
2705
- - A \`React.lazy\` component that can be preloaded using a \`component.preload()\` method.
2706
-
2707
- ## Examples
2708
-
2709
- \`\`\`tsx
2710
- import { lazyRouteComponent } from '@tanstack/react-router'
2711
-
2712
- const route = createRoute({
2713
- path: '/posts/$postId',
2714
- component: lazyRouteComponent(() => import('./Post')), // default export
2715
- })
2716
-
2717
- // or
2718
-
2719
- const route = createRoute({
2720
- path: '/posts/$postId',
2721
- component: lazyRouteComponent(
2722
- () => import('./Post'),
2723
- 'PostByIdPageComponent', // named export
2724
- ),
2725
- })
2726
- \`\`\`
2727
-
2728
- # Link component
2729
-
2730
- The \`Link\` component is a component that can be used to create a link that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.
2731
-
2732
- ## Link props
2733
-
2734
- The \`Link\` component accepts the following props:
2735
-
2736
- ### \`...props\`
2737
-
2738
- - Type: \`LinkProps & React.RefAttributes<HTMLAnchorElement>\`
2739
- - [\`LinkProps\`](../LinkPropsType.md)
2740
-
2741
- ## Link returns
2742
-
2743
- An anchor element that can be used to navigate to a new location.
2744
-
2745
- ## Examples
2746
-
2747
- \`\`\`tsx
2748
- import { Link } from '@tanstack/react-router'
2749
-
2750
- function Component() {
2751
- return (
2752
- <Link
2753
- to="/somewhere/$somewhereId"
2754
- params={{ somewhereId: 'baz' }}
2755
- search={(prev) => ({ ...prev, foo: 'bar' })}
2756
- >
2757
- Click me
2758
- </Link>
2759
- )
2760
- }
2761
- \`\`\`
2762
-
2763
- # Link options
2764
-
2765
- \`linkOptions\` is a function which type checks an object literal with the intention of being used for \`Link\`, \`navigate\` or \`redirect\`
2766
-
2767
- ## linkOptions props
2768
-
2769
- The \`linkOptions\` accepts the following option:
2770
-
2771
- ### \`...props\`
2772
-
2773
- - Type: \`LinkProps & React.RefAttributes<HTMLAnchorElement>\`
2774
- - [\`LinkProps\`](../LinkPropsType.md)
2775
-
2776
- ## \`linkOptions\` returns
2777
-
2778
- An object literal with the exact type inferred from the input
2779
-
2780
- ## Examples
2781
-
2782
- \`\`\`tsx
2783
- const userLinkOptions = linkOptions({
2784
- to: '/dashboard/users/user',
2785
- search: {
2786
- usersView: {
2787
- sortBy: 'email',
2788
- filterBy: 'filter',
2789
- },
2790
- userId: 0,
2791
- },
2792
- })
2793
-
2794
- function DashboardComponent() {
2795
- return <Link {...userLinkOptions} />
2796
- }
2797
- \`\`\`
2798
-
2799
- # MatchRoute component
2800
-
2801
- A component version of the \`useMatchRoute\` hook. It accepts the same options as the \`useMatchRoute\` with additional props to aid in conditional rendering.
2802
-
2803
- ## MatchRoute props
2804
-
2805
- The \`MatchRoute\` component accepts the same options as the \`useMatchRoute\` hook with additional props to aid in conditional rendering.
2806
-
2807
- ### \`...props\` prop
2808
-
2809
- - Type: [\`UseMatchRouteOptions\`](../UseMatchRouteOptionsType.md)
2810
-
2811
- ### \`children\` prop
2812
-
2813
- - Optional
2814
- - \`React.ReactNode\`
2815
- - The component that will be rendered if the route is matched.
2816
- - \`((params: TParams | false) => React.ReactNode)\`
2817
- - A function that will be called with the matched route's params or \`false\` if no route was matched. This can be useful for components that need to always render, but render different props based on a route match or not.
2818
-
2819
- ## MatchRoute returns
2820
-
2821
- Either the \`children\` prop or the return value of the \`children\` function.
2822
-
2823
- ## Examples
2824
-
2825
- \`\`\`tsx
2826
- import { MatchRoute } from '@tanstack/react-router'
2827
-
2828
- function Component() {
2829
- return (
2830
- <div>
2831
- <MatchRoute to="/posts/$postId" params={{ postId: '123' }} pending>
2832
- {(match) => <Spinner show={!!match} wait="delay-50" />}
2833
- </MatchRoute>
2834
- </div>
2835
- )
2836
- }
2837
- \`\`\`
2838
-
2839
- # Navigate component
2840
-
2841
- The \`Navigate\` component is a component that can be used to navigate to a new location when rendered. This includes changes to the pathname, search params, hash, and location state. The underlying navigation will happen inside of a \`useEffect\` hook when successfully rendered.
2842
-
2843
- ## Navigate props
2844
-
2845
- The \`Navigate\` component accepts the following props:
2846
-
2847
- ### \`...options\`
2848
-
2849
- - Type: [\`NavigateOptions\`](../NavigateOptionsType.md)
2850
-
2851
- ## Navigate returns
2852
-
2853
- - \`null\`
2854
-
2855
- # notFound function
2856
-
2857
- The \`notFound\` function returns a new \`NotFoundError\` object that can be either returned or thrown from places like a Route's \`beforeLoad\` or \`loader\` callbacks to trigger the \`notFoundComponent\`.
2858
-
2859
- ## notFound options
2860
-
2861
- The \`notFound\` function accepts a single optional argument, the \`options\` to create the not-found error object.
2862
-
2863
- - Type: [\`Partial<NotFoundError>\`](../NotFoundErrorType.md)
2864
- - Optional
2865
-
2866
- ## notFound returns
2867
-
2868
- - If the \`throw\` property is \`true\` in the \`options\` object, the \`NotFoundError\` object will be thrown from within the function call.
2869
- - If the \`throw\` property is \`false | undefined\` in the \`options\` object, the \`NotFoundError\` object will be returned.
2870
-
2871
- ## Examples
2872
-
2873
- \`\`\`tsx
2874
- import { notFound, createFileRoute, rootRouteId } from '@tanstack/react-router'
2875
-
2876
- const Route = new createFileRoute('/posts/$postId')({
2877
- // throwing a not-found object
2878
- loader: ({ context: { post } }) => {
2879
- if (!post) {
2880
- throw notFound()
2881
- }
2882
- },
2883
- // or if you want to show a not-found on the whole page
2884
- loader: ({ context: { team } }) => {
2885
- if (!team) {
2886
- throw notFound({ routeId: rootRouteId })
2887
- }
2888
- },
2889
- // ... other route options
2890
- })
2891
- \`\`\`
2892
-
2893
- # Outlet component
2894
-
2895
- The \`Outlet\` component is a component that can be used to render the next child route of a parent route.
2896
-
2897
- ## Outlet props
2898
-
2899
- The \`Outlet\` component does not accept any props.
2900
-
2901
- ## Outlet returns
2902
-
2903
- - If matched, the child route match's \`component\`/\`errorComponent\`/\`pendingComponent\`/\`notFoundComponent\`.
2904
- - If not matched, \`null\`.
2905
-
2906
- # redirect function
2907
-
2908
- The \`redirect\` function returns a new \`Redirect\` object that can be either returned or thrown from places like a Route's \`beforeLoad\` or \`loader\` callbacks to trigger _redirect_ to a new location.
2909
-
2910
- ## redirect options
2911
-
2912
- The \`redirect\` function accepts a single argument, the \`options\` to determine the redirect behavior.
2913
-
2914
- - Type: [\`Redirect\`](../RedirectType.md)
2915
- - Required
2916
-
2917
- ## redirect returns
2918
-
2919
- - If the \`throw\` property is \`true\` in the \`options\` object, the \`Redirect\` object will be thrown from within the function call.
2920
- - If the \`throw\` property is \`false | undefined\` in the \`options\` object, the \`Redirect\` object will be returned.
2921
-
2922
- ## Examples
2923
-
2924
- \`\`\`tsx
2925
- import { redirect } from '@tanstack/react-router'
2926
-
2927
- const route = createRoute({
2928
- // throwing a redirect object
2929
- loader: () => {
2930
- if (!user) {
2931
- throw redirect({
2932
- to: '/login',
2933
- })
2934
- }
2935
- },
2936
- // or forcing \`redirect\` to throw itself
2937
- loader: () => {
2938
- if (!user) {
2939
- redirect({
2940
- to: '/login',
2941
- throw: true,
2942
- })
2943
- }
2944
- },
2945
- // ... other route options
2946
- })
2947
- \`\`\`
2948
-
2949
- # Search middleware to retain search params
2950
-
2951
- \`retainSearchParams\` is a search middleware that allows to keep search params.
2952
-
2953
- ## retainSearchParams props
2954
-
2955
- The \`retainSearchParams\` either accepts \`true\` or a list of keys of those search params that shall be retained.
2956
- If \`true\` is passed in, all search params will be retained.
2957
-
2958
- ## Examples
2959
-
2960
- \`\`\`tsx
2961
- import { z } from 'zod'
2962
- import { createRootRoute, retainSearchParams } from '@tanstack/react-router'
2963
- import { zodValidator } from '@tanstack/zod-adapter'
2964
-
2965
- const searchSchema = z.object({
2966
- rootValue: z.string().optional(),
2967
- })
2968
-
2969
- export const Route = createRootRoute({
2970
- validateSearch: zodValidator(searchSchema),
2971
- search: {
2972
- middlewares: [retainSearchParams(['rootValue'])],
2973
- },
2974
- })
2975
- \`\`\`
2976
-
2977
- \`\`\`tsx
2978
- import { z } from 'zod'
2979
- import { createFileRoute, retainSearchParams } from '@tanstack/react-router'
2980
- import { zodValidator } from '@tanstack/zod-adapter'
2981
-
2982
- const searchSchema = z.object({
2983
- one: z.string().optional(),
2984
- two: z.string().optional(),
2985
- })
2986
-
2987
- export const Route = createFileRoute({
2988
- validateSearch: zodValidator(searchSchema),
2989
- search: {
2990
- middlewares: [retainSearchParams(true)],
2991
- },
2992
- })
2993
- \`\`\`
2994
-
2995
- # rootRouteWithContext function
2996
-
2997
- > [!CAUTION]
2998
- > This function is deprecated and will be removed in the next major version of TanStack Router.
2999
- > Please use the [\`createRootRouteWithContext\`](../createRootRouteWithContextFunction.md) function instead.
3000
-
3001
- The \`rootRouteWithContext\` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created.
3002
-
3003
- ## rootRouteWithContext generics
3004
-
3005
- The \`rootRouteWithContext\` function accepts a single generic argument:
3006
-
3007
- ### \`TRouterContext\` generic
3008
-
3009
- - Type: \`TRouterContext\`
3010
- - Optional, **but recommended**.
3011
- - The context type that will be required to be fulfilled when the router is created
3012
-
3013
- ## rootRouteWithContext returns
3014
-
3015
- - A factory function that can be used to create a new [\`createRootRoute\`](../createRootRouteFunction.md) instance.
3016
- - It accepts a single argument, the same as the [\`createRootRoute\`](../createRootRouteFunction.md) function.
3017
-
3018
- ## Examples
3019
-
3020
- \`\`\`tsx
3021
- import { rootRouteWithContext, createRouter } from '@tanstack/react-router'
3022
- import { QueryClient } from '@tanstack/react-query'
3023
-
3024
- interface MyRouterContext {
3025
- queryClient: QueryClient
3026
- }
3027
-
3028
- const rootRoute = rootRouteWithContext<MyRouterContext>()({
3029
- component: () => <Outlet />,
3030
- // ... root route options
3031
- })
3032
-
3033
- const routeTree = rootRoute.addChildren([
3034
- // ... other routes
3035
- ])
3036
-
3037
- const queryClient = new QueryClient()
3038
-
3039
- const router = createRouter({
3040
- routeTree,
3041
- context: {
3042
- queryClient,
3043
- },
3044
- })
3045
- \`\`\`
3046
-
3047
- # Search middleware to strip search params
3048
-
3049
- \`stripSearchParams\` is a search middleware that allows to remove search params.
3050
-
3051
- ## stripSearchParams props
3052
-
3053
- \`stripSearchParams\` accepts one of the following inputs:
3054
-
3055
- - \`true\`: if the search schema has no required params, \`true\` can be used to strip all search params
3056
- - a list of keys of those search params that shall be removed; only keys of optional search params are allowed.
3057
- - an object that conforms to the partial input search schema. The search params are compared against the values of this object; if the value is deeply equal, it will be removed. This is especially useful to strip out default search params.
3058
-
3059
- ## Examples
3060
-
3061
- \`\`\`tsx
3062
- import { z } from 'zod'
3063
- import { createFileRoute, stripSearchParams } from '@tanstack/react-router'
3064
- import { zodValidator } from '@tanstack/zod-adapter'
3065
-
3066
- const defaultValues = {
3067
- one: 'abc',
3068
- two: 'xyz',
3069
- }
3070
-
3071
- const searchSchema = z.object({
3072
- one: z.string().default(defaultValues.one),
3073
- two: z.string().default(defaultValues.two),
3074
- })
3075
-
3076
- export const Route = createFileRoute({
3077
- validateSearch: zodValidator(searchSchema),
3078
- search: {
3079
- // strip default values
3080
- middlewares: [stripSearchParams(defaultValues)],
3081
- },
3082
- })
3083
- \`\`\`
3084
-
3085
- \`\`\`tsx
3086
- import { z } from 'zod'
3087
- import { createRootRoute, stripSearchParams } from '@tanstack/react-router'
3088
- import { zodValidator } from '@tanstack/zod-adapter'
3089
-
3090
- const searchSchema = z.object({
3091
- hello: z.string().default('world'),
3092
- requiredParam: z.string(),
3093
- })
3094
-
3095
- export const Route = createRootRoute({
3096
- validateSearch: zodValidator(searchSchema),
3097
- search: {
3098
- // always remove \`hello\`
3099
- middlewares: [stripSearchParams(['hello'])],
3100
- },
3101
- })
3102
- \`\`\`
3103
-
3104
- \`\`\`tsx
3105
- import { z } from 'zod'
3106
- import { createFileRoute, stripSearchParams } from '@tanstack/react-router'
3107
- import { zodValidator } from '@tanstack/zod-adapter'
3108
-
3109
- const searchSchema = z.object({
3110
- one: z.string().default('abc'),
3111
- two: z.string().default('xyz'),
3112
- })
3113
-
3114
- export const Route = createFileRoute({
3115
- validateSearch: zodValidator(searchSchema),
3116
- search: {
3117
- // remove all search params
3118
- middlewares: [stripSearchParams(true)],
3119
- },
3120
- })
3121
- \`\`\`
3122
-
3123
- # useAwaited hook
3124
-
3125
- The \`useAwaited\` method is a hook that suspends until the provided promise is resolved or rejected.
3126
-
3127
- ## useAwaited options
3128
-
3129
- The \`useAwaited\` hook accepts a single argument, an \`options\` object.
3130
-
3131
- ### \`options.promise\` option
3132
-
3133
- - Type: \`Promise<T>\`
3134
- - Required
3135
- - The deferred promise to await.
3136
-
3137
- ## useAwaited returns
3138
-
3139
- - Throws an error if the promise is rejected.
3140
- - Suspends (throws a promise) if the promise is pending.
3141
- - Returns the resolved value of a deferred promise if the promise is resolved.
3142
-
3143
- ## Examples
3144
-
3145
- \`\`\`tsx
3146
- import { useAwaited } from '@tanstack/react-router'
3147
-
3148
- function Component() {
3149
- const { deferredPromise } = route.useLoaderData()
3150
-
3151
- const data = useAwaited({ promise: myDeferredPromise })
3152
- // ...
3153
- }
3154
- \`\`\`
3155
-
3156
- # useBlocker hook
3157
-
3158
- The \`useBlocker\` method is a hook that [blocks navigation](../../../guide/navigation-blocking.md) when a condition is met.
3159
-
3160
- > ⚠️ The following new \`useBlocker\` API is currently _experimental_.
3161
-
3162
- ## useBlocker options
3163
-
3164
- The \`useBlocker\` hook accepts a single _required_ argument, an option object:
3165
-
3166
- ### \`options.shouldBlockFn\` option
3167
-
3168
- - Required
3169
- - Type: \`ShouldBlockFn\`
3170
- - This function should return a \`boolean\` or a \`Promise<boolean>\` that tells the blocker if it should block the current navigation
3171
- - The function has the argument of type \`ShouldBlockFnArgs\` passed to it, which tells you information about the current and next route and the action performed
3172
- - Think of this function as telling the router if it should block the navigation, so returning \`true\` mean that it should block the navigation and \`false\` meaning that it should be allowed
3173
-
3174
- \`\`\`ts
3175
- interface ShouldBlockFnLocation<...> {
3176
- routeId: TRouteId
3177
- fullPath: TFullPath
3178
- pathname: string
3179
- params: TAllParams
3180
- search: TFullSearchSchema
3181
- }
3182
-
3183
- type ShouldBlockFnArgs = {
3184
- current: ShouldBlockFnLocation
3185
- next: ShouldBlockFnLocation
3186
- action: HistoryAction
3187
- }
3188
- \`\`\`
3189
-
3190
- ### \`options.disabled\` option
3191
-
3192
- - Optional - defaults to \`false\`
3193
- - Type: \`boolean\`
3194
- - Specifies if the blocker should be entirely disabled or not
3195
-
3196
- ### \`options.enableBeforeUnload\` option
3197
-
3198
- - Optional - defaults to \`true\`
3199
- - Type: \`boolean | (() => boolean)\`
3200
- - Tell the blocker to sometimes or always block the browser \`beforeUnload\` event or not
3201
-
3202
- ### \`options.withResolver\` option
3203
-
3204
- - Optional - defaults to \`false\`
3205
- - Type: \`boolean\`
3206
- - Specify if the resolver returned by the hook should be used or whether your \`shouldBlockFn\` function itself resolves the blocking
3207
-
3208
- ### \`options.blockerFn\` option (⚠️ deprecated)
3209
-
3210
- - Optional
3211
- - Type: \`BlockerFn\`
3212
- - The function that returns a \`boolean\` or \`Promise<boolean>\` indicating whether to allow navigation.
3213
-
3214
- ### \`options.condition\` option (⚠️ deprecated)
3215
-
3216
- - Optional - defaults to \`true\`
3217
- - Type: \`boolean\`
3218
- - A navigation attempt is blocked when this condition is \`true\`.
3219
-
3220
- ## useBlocker returns
3221
-
3222
- An object with the controls to allow manual blocking and unblocking of navigation.
3223
-
3224
- - \`status\` - A string literal that can be either \`'blocked'\` or \`'idle'\`
3225
- - \`next\` - When status is \`blocked\`, a type narrrowable object that contains information about the next location
3226
- - \`current\` - When status is \`blocked\`, a type narrrowable object that contains information about the current location
3227
- - \`action\` - When status is \`blocked\`, a \`HistoryAction\` string that shows the action that triggered the navigation
3228
- - \`proceed\` - When status is \`blocked\`, a function that allows navigation to continue
3229
- - \`reset\` - When status is \`blocked\`, a function that cancels navigation (\`status\` will be reset to \`'idle'\`)
3230
-
3231
- or
3232
-
3233
- \`void\` when \`withResolver\` is \`false\`
3234
-
3235
- ## Examples
3236
-
3237
- Two common use cases for the \`useBlocker\` hook are:
3238
-
3239
- ### Basic usage
3240
-
3241
- \`\`\`tsx
3242
- import { useBlocker } from '@tanstack/react-router'
3243
-
3244
- function MyComponent() {
3245
- const [formIsDirty, setFormIsDirty] = useState(false)
3246
-
3247
- useBlocker({
3248
- shouldBlockFn: () => formIsDirty,
3249
- })
3250
-
3251
- // ...
3252
- }
3253
- \`\`\`
3254
-
3255
- ### Custom UI
3256
-
3257
- \`\`\`tsx
3258
- import { useBlocker } from '@tanstack/react-router'
3259
-
3260
- function MyComponent() {
3261
- const [formIsDirty, setFormIsDirty] = useState(false)
3262
-
3263
- const { proceed, reset, status, next } = useBlocker({
3264
- shouldBlockFn: () => formIsDirty,
3265
- withResolver: true,
3266
- })
3267
-
3268
- // ...
3269
-
3270
- return (
3271
- <>
3272
- {/* ... */}
3273
- {status === 'blocked' && (
3274
- <div>
3275
- <p>You are navigating to {next.pathname}</p>
3276
- <p>Are you sure you want to leave?</p>
3277
- <button onClick={proceed}>Yes</button>
3278
- <button onClick={reset}>No</button>
3279
- </div>
3280
- )}
3281
- </>
3282
- }
3283
- \`\`\`
3284
-
3285
- ### Conditional blocking
3286
-
3287
- \`\`\`tsx
3288
- import { useBlocker } from '@tanstack/react-router'
3289
-
3290
- function MyComponent() {
3291
- const { proceed, reset, status } = useBlocker({
3292
- shouldBlockFn: ({ next }) => {
3293
- return !next.pathname.includes('step/')
3294
- },
3295
- withResolver: true,
3296
- })
3297
-
3298
- // ...
3299
-
3300
- return (
3301
- <>
3302
- {/* ... */}
3303
- {status === 'blocked' && (
3304
- <div>
3305
- <p>Are you sure you want to leave?</p>
3306
- <button onClick={proceed}>Yes</button>
3307
- <button onClick={reset}>No</button>
3308
- </div>
3309
- )}
3310
- </>
3311
- )
3312
- }
3313
- \`\`\`
3314
-
3315
- ### Without resolver
3316
-
3317
- \`\`\`tsx
3318
- import { useBlocker } from '@tanstack/react-router'
3319
-
3320
- function MyComponent() {
3321
- const [formIsDirty, setFormIsDirty] = useState(false)
3322
-
3323
- useBlocker({
3324
- shouldBlockFn: ({ next }) => {
3325
- if (next.pathname.includes('step/')) {
3326
- return false
3327
- }
3328
-
3329
- const shouldLeave = confirm('Are you sure you want to leave?')
3330
- return !shouldLeave
3331
- },
3332
- })
3333
-
3334
- // ...
3335
- }
3336
- \`\`\`
3337
-
3338
- ### Type narrowing
3339
-
3340
- \`\`\`tsx
3341
- import { useBlocker } from '@tanstack/react-router'
3342
-
3343
- function MyComponent() {
3344
- const [formIsDirty, setFormIsDirty] = useState(false)
3345
-
3346
- // block going from editor-1 to /foo/123?hello=world
3347
- const { proceed, reset, status } = useBlocker({
3348
- shouldBlockFn: ({ current, next }) => {
3349
- if (
3350
- current.routeId === '/editor-1' &&
3351
- next.fullPath === '/foo/$id' &&
3352
- next.params.id === '123' &&
3353
- next.search.hello === 'world'
3354
- ) {
3355
- return true
3356
- }
3357
- return false
3358
- },
3359
- enableBeforeUnload: false,
3360
- withResolver: true,
3361
- })
3362
-
3363
- // ...
3364
- }
3365
- \`\`\`
3366
-
3367
- # useCanGoBack hook
3368
-
3369
- The \`useCanGoBack\` hook returns a boolean representing if the router history can safely go back without exiting the application.
3370
-
3371
- > ⚠️ The following new \`useCanGoBack\` API is currently _experimental_.
3372
-
3373
- ## useCanGoBack returns
3374
-
3375
- - If the router history is not at index \`0\`, \`true\`.
3376
- - If the router history is at index \`0\`, \`false\`.
3377
-
3378
- ## Limitations
3379
-
3380
- The router history index is reset after a navigation with [\`reloadDocument\`](../NavigateOptionsType.md#reloaddocument) set as \`true\`. This causes the router history to consider the new location as the initial one and will cause \`useCanGoBack\` to return \`false\`.
3381
-
3382
- ## Examples
3383
-
3384
- ### Showing a back button
3385
-
3386
- \`\`\`tsx
3387
- import { useRouter, useCanGoBack } from '@tanstack/react-router'
3388
-
3389
- function Component() {
3390
- const router = useRouter()
3391
- const canGoBack = useCanGoBack()
3392
-
3393
- return (
3394
- <div>
3395
- {canGoBack ? (
3396
- <button onClick={() => router.history.back()}>Go back</button>
3397
- ) : null}
3398
-
3399
- {/* ... */}
3400
- </div>
3401
- )
3402
- }
3403
- \`\`\`
3404
-
3405
- # useChildMatches hook
3406
-
3407
- The \`useChildMatches\` hook returns all of the child [\`RouteMatch\`](../RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the \`useMatch\` hook.**
3408
-
3409
- > [!IMPORTANT]
3410
- > If the router has pending matches and they are showing their pending component fallbacks, \`router.state.pendingMatches\` will used instead of \`router.state.matches\`.
3411
-
3412
- ## useChildMatches options
3413
-
3414
- The \`useChildMatches\` hook accepts a single _optional_ argument, an \`options\` object.
3415
-
3416
- ### \`opts.select\` option
3417
-
3418
- - Optional
3419
- - \`(matches: RouteMatch[]) => TSelected\`
3420
- - If supplied, this function will be called with the route matches and the return value will be returned from \`useChildMatches\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
3421
-
3422
- ### \`opts.structuralSharing\` option
3423
-
3424
- - Type: \`boolean\`
3425
- - Optional
3426
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
3427
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
3428
-
3429
- ## useChildMatches returns
3430
-
3431
- - If a \`select\` function is provided, the return value of the \`select\` function.
3432
- - If no \`select\` function is provided, an array of [\`RouteMatch\`](../RouteMatchType.md) objects.
3433
-
3434
- ## Examples
3435
-
3436
- \`\`\`tsx
3437
- import { useChildMatches } from '@tanstack/react-router'
3438
-
3439
- function Component() {
3440
- const childMatches = useChildMatches()
3441
- // ...
3442
- }
3443
- \`\`\`
3444
-
3445
- # useLinkProps hook
3446
-
3447
- The \`useLinkProps\` hook that takes an object as its argument and returns a \`React.AnchorHTMLAttributes<HTMLAnchorElement>\` props object. These props can then be safely applied to an anchor element to create a link that can be used to navigate to the new location. This includes changes to the pathname, search params, hash, and location state.
3448
-
3449
- ## useLinkProps options
3450
-
3451
- \`\`\`tsx
3452
- type UseLinkPropsOptions = ActiveLinkOptions &
3453
- React.AnchorHTMLAttributes<HTMLAnchorElement>
3454
- \`\`\`
3455
-
3456
- - [\`ActiveLinkOptions\`](../ActiveLinkOptionsType.md)
3457
- - The \`useLinkProps\` options are used to build a [\`LinkProps\`](../LinkPropsType.md) object.
3458
- - It also extends the \`React.AnchorHTMLAttributes<HTMLAnchorElement>\` type, so that any additional props that are passed to the \`useLinkProps\` hook will be merged with the [\`LinkProps\`](../LinkPropsType.md) object.
3459
-
3460
- ## useLinkProps returns
3461
-
3462
- - A \`React.AnchorHTMLAttributes<HTMLAnchorElement>\` object that can be applied to an anchor element to create a link that can be used to navigate to the new location
3463
-
3464
- # useLoaderData hook
3465
-
3466
- The \`useLoaderData\` hook returns the loader data from the closest [\`RouteMatch\`](../RouteMatchType.md) in the component tree.
3467
-
3468
- ## useLoaderData options
3469
-
3470
- The \`useLoaderData\` hook accepts an \`options\` object.
3471
-
3472
- ### \`opts.from\` option
3473
-
3474
- - Type: \`string\`
3475
- - The route id of the closest parent match
3476
- - Optional, but recommended for full type safety.
3477
- - If \`opts.strict\` is \`true\`, TypeScript will warn for this option if it is not provided.
3478
- - If \`opts.strict\` is \`false\`, TypeScript will provided loosened types for the returned loader data.
3479
-
3480
- ### \`opts.strict\` option
3481
-
3482
- - Type: \`boolean\`
3483
- - Optional - \`default: true\`
3484
- - If \`false\`, the \`opts.from\` option will be ignored and types will be loosened to to reflect the shared types of all possible loader data.
3485
-
3486
- ### \`opts.select\` option
3487
-
3488
- - Optional
3489
- - \`(loaderData: TLoaderData) => TSelected\`
3490
- - If supplied, this function will be called with the loader data and the return value will be returned from \`useLoaderData\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
3491
-
3492
- ### \`opts.structuralSharing\` option
3493
-
3494
- - Type: \`boolean\`
3495
- - Optional
3496
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
3497
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
3498
-
3499
- ## useLoaderData returns
3500
-
3501
- - If a \`select\` function is provided, the return value of the \`select\` function.
3502
- - If no \`select\` function is provided, the loader data or a loosened version of the loader data if \`opts.strict\` is \`false\`.
3503
-
3504
- ## Examples
3505
-
3506
- \`\`\`tsx
3507
- import { useLoaderData } from '@tanstack/react-router'
3508
-
3509
- function Component() {
3510
- const loaderData = useLoaderData({ from: '/posts/$postId' })
3511
- // ^? { postId: string, body: string, ... }
3512
- // ...
3513
- }
3514
- \`\`\`
3515
-
3516
- # useLoaderDeps hook
3517
-
3518
- The \`useLoaderDeps\` hook is a hook that returns an object with the dependencies that are used to trigger the \`loader\` for a given route.
3519
-
3520
- ## useLoaderDepsHook options
3521
-
3522
- The \`useLoaderDepsHook\` hook accepts an \`options\` object.
3523
-
3524
- ### \`opts.from\` option
3525
-
3526
- - Type: \`string\`
3527
- - Required
3528
- - The RouteID or path to get the loader dependencies from.
3529
-
3530
- ### \`opts.select\` option
3531
-
3532
- - Type: \`(deps: TLoaderDeps) => TSelected\`
3533
- - Optional
3534
- - If supplied, this function will be called with the loader dependencies object and the return value will be returned from \`useLoaderDeps\`.
3535
-
3536
- ### \`opts.structuralSharing\` option
3537
-
3538
- - Type: \`boolean\`
3539
- - Optional
3540
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
3541
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
3542
-
3543
- ## useLoaderDeps returns
3544
-
3545
- - An object of the loader dependencies or \`TSelected\` if a \`select\` function is provided.
3546
-
3547
- ## Examples
3548
-
3549
- \`\`\`tsx
3550
- import { useLoaderDeps } from '@tanstack/react-router'
3551
-
3552
- const routeApi = getRouteApi('/posts/$postId')
3553
-
3554
- function Component() {
3555
- const deps = useLoaderDeps({ from: '/posts/$postId' })
3556
-
3557
- // OR
3558
-
3559
- const routeDeps = routeApi.useLoaderDeps()
3560
-
3561
- // OR
3562
-
3563
- const postId = useLoaderDeps({
3564
- from: '/posts',
3565
- select: (deps) => deps.view,
3566
- })
3567
-
3568
- // ...
3569
- }
3570
- \`\`\`
3571
-
3572
- # useLocation hook
3573
-
3574
- The \`useLocation\` method is a hook that returns the current [\`location\`](../ParsedLocationType.md) object. This hook is useful for when you want to perform some side effect whenever the current location changes.
3575
-
3576
- ## useLocation options
3577
-
3578
- The \`useLocation\` hook accepts an optional \`options\` object.
3579
-
3580
- ### \`opts.select\` option
3581
-
3582
- - Type: \`(state: ParsedLocationType) => TSelected\`
3583
- - Optional
3584
- - If supplied, this function will be called with the [\`location\`](../ParsedLocationType.md) object and the return value will be returned from \`useLocation\`.
3585
-
3586
- ## useLocation returns
3587
-
3588
- - The current [\`location\`](../ParsedLocationType.md) object or \`TSelected\` if a \`select\` function is provided.
3589
-
3590
- ## Examples
3591
-
3592
- \`\`\`tsx
3593
- import { useLocation } from '@tanstack/react-router'
3594
-
3595
- function Component() {
3596
- const location = useLocation()
3597
- // ^ ParsedLocation
3598
-
3599
- // OR
3600
-
3601
- const pathname = useLocation({
3602
- select: (location) => location.pathname,
3603
- })
3604
- // ^ string
3605
-
3606
- // ...
3607
- }
3608
- \`\`\`
3609
-
3610
- # useMatch hook
3611
-
3612
- The \`useMatch\` hook returns a [\`RouteMatch\`](../RouteMatchType.md) in the component tree. The raw route match contains all of the information about a route match in the router and also powers many other hooks under the hood like \`useParams\`, \`useLoaderData\`, \`useRouteContext\`, and \`useSearch\`.
3613
-
3614
- ## useMatch options
3615
-
3616
- The \`useMatch\` hook accepts a single argument, an \`options\` object.
3617
-
3618
- ### \`opts.from\` option
3619
-
3620
- - Type: \`string\`
3621
- - The route id of a match
3622
- - Optional, but recommended for full type safety.
3623
- - If \`opts.strict\` is \`true\`, \`from\` is required and TypeScript will warn for this option if it is not provided.
3624
- - If \`opts.strict\` is \`false\`, \`from\` must not be set and TypeScript will provided loosened types for the returned [\`RouteMatch\`](../RouteMatchType.md).
3625
-
3626
- ### \`opts.strict\` option
3627
-
3628
- - Type: \`boolean\`
3629
- - Optional
3630
- - \`default: true\`
3631
- - If \`false\`, the \`opts.from\` must not be set and types will be loosened to \`Partial<RouteMatch>\` to reflect the shared types of all matches.
3632
-
3633
- ### \`opts.select\` option
3634
-
3635
- - Optional
3636
- - \`(match: RouteMatch) => TSelected\`
3637
- - If supplied, this function will be called with the route match and the return value will be returned from \`useMatch\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
3638
-
3639
- ### \`opts.structuralSharing\` option
3640
-
3641
- - Type: \`boolean\`
3642
- - Optional
3643
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
3644
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
3645
-
3646
- ### \`opts.shouldThrow\` option
3647
-
3648
- - Type: \`boolean\`
3649
- - Optional
3650
- - \`default: true\`
3651
- - If \`false\`,\`useMatch\` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return \`undefined\`.
3652
-
3653
- ## useMatch returns
3654
-
3655
- - If a \`select\` function is provided, the return value of the \`select\` function.
3656
- - If no \`select\` function is provided, the [\`RouteMatch\`](../RouteMatchType.md) object or a loosened version of the \`RouteMatch\` object if \`opts.strict\` is \`false\`.
3657
-
3658
- ## Examples
3659
-
3660
- ### Accessing a route match
3661
-
3662
- \`\`\`tsx
3663
- import { useMatch } from '@tanstack/react-router'
3664
-
3665
- function Component() {
3666
- const match = useMatch({ from: '/posts/$postId' })
3667
- // ^? strict match for RouteMatch
3668
- // ...
3669
- }
3670
- \`\`\`
3671
-
3672
- ### Accessing the root route's match
3673
-
3674
- \`\`\`tsx
3675
- import {
3676
- useMatch,
3677
- rootRouteId, // <<<< use this token!
3678
- } from '@tanstack/react-router'
3679
-
3680
- function Component() {
3681
- const match = useMatch({ from: rootRouteId })
3682
- // ^? strict match for RouteMatch
3683
- // ...
3684
- }
3685
- \`\`\`
3686
-
3687
- ### Checking if a specific route is currently rendered
3688
-
3689
- \`\`\`tsx
3690
- import { useMatch } from '@tanstack/react-router'
3691
-
3692
- function Component() {
3693
- const match = useMatch({ from: '/posts', shouldThrow: false })
3694
- // ^? RouteMatch | undefined
3695
- if (match !== undefined) {
3696
- // ...
3697
- }
3698
- }
3699
- \`\`\`
3700
-
3701
- # useMatchRoute hook
3702
-
3703
- The \`useMatchRoute\` hook is a hook that returns a \`matchRoute\` function that can be used to match a route against either the current or pending location.
3704
-
3705
- ## useMatchRoute returns
3706
-
3707
- - A \`matchRoute\` function that can be used to match a route against either the current or pending location.
3708
-
3709
- ## matchRoute function
3710
-
3711
- The \`matchRoute\` function is a function that can be used to match a route against either the current or pending location.
3712
-
3713
- ### matchRoute function options
3714
-
3715
- The \`matchRoute\` function accepts a single argument, an \`options\` object.
3716
-
3717
- - Type: [\`UseMatchRouteOptions\`](../UseMatchRouteOptionsType.md)
3718
-
3719
- ### matchRoute function returns
3720
-
3721
- - The matched route's params or \`false\` if no route was matched
3722
-
3723
- ## Examples
3724
-
3725
- \`\`\`tsx
3726
- import { useMatchRoute } from '@tanstack/react-router'
3727
-
3728
- // Current location: /posts/123
3729
- function Component() {
3730
- const matchRoute = useMatchRoute()
3731
- const params = matchRoute({ to: '/posts/$postId' })
3732
- // ^ { postId: '123' }
3733
- }
3734
-
3735
- // Current location: /posts/123
3736
- function Component() {
3737
- const matchRoute = useMatchRoute()
3738
- const params = matchRoute({ to: '/posts' })
3739
- // ^ false
3740
- }
3741
-
3742
- // Current location: /posts/123
3743
- function Component() {
3744
- const matchRoute = useMatchRoute()
3745
- const params = matchRoute({ to: '/posts', fuzzy: true })
3746
- // ^ {}
3747
- }
3748
-
3749
- // Current location: /posts
3750
- // Pending location: /posts/123
3751
- function Component() {
3752
- const matchRoute = useMatchRoute()
3753
- const params = matchRoute({ to: '/posts/$postId', pending: true })
3754
- // ^ { postId: '123' }
3755
- }
3756
-
3757
- // Current location: /posts/123/foo/456
3758
- function Component() {
3759
- const matchRoute = useMatchRoute()
3760
- const params = matchRoute({ to: '/posts/$postId/foo/$fooId' })
3761
- // ^ { postId: '123', fooId: '456' }
3762
- }
3763
-
3764
- // Current location: /posts/123/foo/456
3765
- function Component() {
3766
- const matchRoute = useMatchRoute()
3767
- const params = matchRoute({
3768
- to: '/posts/$postId/foo/$fooId',
3769
- params: { postId: '123' },
3770
- })
3771
- // ^ { postId: '123', fooId: '456' }
3772
- }
3773
-
3774
- // Current location: /posts/123/foo/456
3775
- function Component() {
3776
- const matchRoute = useMatchRoute()
3777
- const params = matchRoute({
3778
- to: '/posts/$postId/foo/$fooId',
3779
- params: { postId: '789' },
3780
- })
3781
- // ^ false
3782
- }
3783
-
3784
- // Current location: /posts/123/foo/456
3785
- function Component() {
3786
- const matchRoute = useMatchRoute()
3787
- const params = matchRoute({
3788
- to: '/posts/$postId/foo/$fooId',
3789
- params: { fooId: '456' },
3790
- })
3791
- // ^ { postId: '123', fooId: '456' }
3792
- }
3793
-
3794
- // Current location: /posts/123/foo/456
3795
- function Component() {
3796
- const matchRoute = useMatchRoute()
3797
- const params = matchRoute({
3798
- to: '/posts/$postId/foo/$fooId',
3799
- params: { postId: '123', fooId: '456' },
3800
- })
3801
- // ^ { postId: '123', fooId: '456' }
3802
- }
3803
-
3804
- // Current location: /posts/123/foo/456
3805
- function Component() {
3806
- const matchRoute = useMatchRoute()
3807
- const params = matchRoute({
3808
- to: '/posts/$postId/foo/$fooId',
3809
- params: { postId: '789', fooId: '456' },
3810
- })
3811
- // ^ false
3812
- }
3813
- \`\`\`
3814
-
3815
- # useMatches hook
3816
-
3817
- The \`useMatches\` hook returns all of the [\`RouteMatch\`](../RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**.
3818
-
3819
- > [!TIP]
3820
- > If you only want the parent or child matches, then you can use the [\`useParentMatches\`](../useParentMatchesHook.md) or the [\`useChildMatches\`](../useChildMatchesHook.md) based on the selection you need.
3821
-
3822
- ## useMatches options
3823
-
3824
- The \`useMatches\` hook accepts a single _optional_ argument, an \`options\` object.
3825
-
3826
- ### \`opts.select\` option
3827
-
3828
- - Optional
3829
- - \`(matches: RouteMatch[]) => TSelected\`
3830
- - If supplied, this function will be called with the route matches and the return value will be returned from \`useMatches\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
3831
-
3832
- ### \`opts.structuralSharing\` option
3833
-
3834
- - Type: \`boolean\`
3835
- - Optional
3836
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
3837
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
3838
-
3839
- ## useMatches returns
3840
-
3841
- - If a \`select\` function is provided, the return value of the \`select\` function.
3842
- - If no \`select\` function is provided, an array of [\`RouteMatch\`](../RouteMatchType.md) objects.
3843
-
3844
- ## Examples
3845
-
3846
- \`\`\`tsx
3847
- import { useMatches } from '@tanstack/react-router'
3848
-
3849
- function Component() {
3850
- const matches = useMatches()
3851
- // ^? [RouteMatch, RouteMatch, ...]
3852
- // ...
3853
- }
3854
- \`\`\`
3855
-
3856
- # useNavigate hook
3857
-
3858
- The \`useNavigate\` hook is a hook that returns a \`navigate\` function that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.
3859
-
3860
- ## useNavigate options
3861
-
3862
- The \`useNavigate\` hook accepts a single argument, an \`options\` object.
3863
-
3864
- ### \`opts.from\` option
3865
-
3866
- - Type: \`string\`
3867
- - Optional
3868
- - Description: The location to navigate from. This is useful when you want to navigate to a new location from a specific location, rather than the current location.
3869
-
3870
- ## useNavigate returns
3871
-
3872
- - A \`navigate\` function that can be used to navigate to a new location.
3873
-
3874
- ## navigate function
3875
-
3876
- The \`navigate\` function is a function that can be used to navigate to a new location.
3877
-
3878
- ### navigate function options
3879
-
3880
- The \`navigate\` function accepts a single argument, an \`options\` object.
3881
-
3882
- - Type: [\`NavigateOptions\`](../NavigateOptionsType.md)
3883
-
3884
- ### navigate function returns
3885
-
3886
- - A \`Promise\` that resolves when the navigation is complete
3887
-
3888
- ## Examples
3889
-
3890
- \`\`\`tsx
3891
- import { useNavigate } from '@tanstack/react-router'
3892
-
3893
- function PostsPage() {
3894
- const navigate = useNavigate({ from: '/posts' })
3895
- const handleClick = () => navigate({ search: { page: 2 } })
3896
- // ...
3897
- }
3898
-
3899
- function Component() {
3900
- const navigate = useNavigate()
3901
- return (
3902
- <div>
3903
- <button
3904
- onClick={() =>
3905
- navigate({
3906
- to: '/posts',
3907
- })
3908
- }
3909
- >
3910
- Posts
3911
- </button>
3912
- <button
3913
- onClick={() =>
3914
- navigate({
3915
- to: '/posts',
3916
- search: { page: 2 },
3917
- })
3918
- }
3919
- >
3920
- Posts (Page 2)
3921
- </button>
3922
- <button
3923
- onClick={() =>
3924
- navigate({
3925
- to: '/posts',
3926
- hash: 'my-hash',
3927
- })
3928
- }
3929
- >
3930
- Posts (Hash)
3931
- </button>
3932
- <button
3933
- onClick={() =>
3934
- navigate({
3935
- to: '/posts',
3936
- state: { from: 'home' },
3937
- })
3938
- }
3939
- >
3940
- Posts (State)
3941
- </button>
3942
- </div>
3943
- )
3944
- }
3945
- \`\`\`
3946
-
3947
- # useParams hook
3948
-
3949
- The \`useParams\` method returns all of the path parameters that were parsed for the closest match and all of its parent matches.
3950
-
3951
- ## useParams options
3952
-
3953
- The \`useParams\` hook accepts an optional \`options\` object.
3954
-
3955
- ### \`opts.strict\` option
3956
-
3957
- - Type: \`boolean\`
3958
- - Optional - \`default: true\`
3959
- - If \`false\`, the \`opts.from\` option will be ignored and types will be loosened to \`Partial<AllParams>\` to reflect the shared types of all params.
3960
-
3961
- ### \`opts.shouldThrow\` option
3962
-
3963
- - Type: \`boolean\`
3964
- - Optional
3965
- - \`default: true\`
3966
- - If \`false\`,\`useParams\` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return \`undefined\`.
3967
-
3968
- ### \`opts.select\` option
3969
-
3970
- - Optional
3971
- - \`(params: AllParams) => TSelected\`
3972
- - If supplied, this function will be called with the params object and the return value will be returned from \`useParams\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
3973
-
3974
- ### \`opts.structuralSharing\` option
3975
-
3976
- - Type: \`boolean\`
3977
- - Optional
3978
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
3979
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
3980
-
3981
- ## useParams returns
3982
-
3983
- - An object of of the match's and parent match path params or \`TSelected\` if a \`select\` function is provided.
3984
-
3985
- ## Examples
3986
-
3987
- \`\`\`tsx
3988
- import { useParams } from '@tanstack/react-router'
3989
-
3990
- const routeApi = getRouteApi('/posts/$postId')
3991
-
3992
- function Component() {
3993
- const params = useParams({ from: '/posts/$postId' })
3994
-
3995
- // OR
3996
-
3997
- const routeParams = routeApi.useParams()
3998
-
3999
- // OR
4000
-
4001
- const postId = useParams({
4002
- from: '/posts/$postId',
4003
- select: (params) => params.postId,
4004
- })
4005
-
4006
- // OR
4007
-
4008
- const looseParams = useParams({ strict: false })
4009
-
4010
- // ...
4011
- }
4012
- \`\`\`
4013
-
4014
- # useParentMatches hook
4015
-
4016
- The \`useParentMatches\` hook returns all of the parent [\`RouteMatch\`](../RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the \`useMatch\` hook.**
4017
-
4018
- > [!IMPORTANT]
4019
- > If the router has pending matches and they are showing their pending component fallbacks, \`router.state.pendingMatches\` will used instead of \`router.state.matches\`.
4020
-
4021
- ## useParentMatches options
4022
-
4023
- The \`useParentMatches\` hook accepts an optional \`options\` object.
4024
-
4025
- ### \`opts.select\` option
4026
-
4027
- - Optional
4028
- - \`(matches: RouteMatch[]) => TSelected\`
4029
- - If supplied, this function will be called with the route matches and the return value will be returned from \`useParentMatches\`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.
4030
-
4031
- ### \`opts.structuralSharing\` option
4032
-
4033
- - Type: \`boolean\`
4034
- - Optional
4035
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
4036
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
4037
-
4038
- ## useParentMatches returns
4039
-
4040
- - If a \`select\` function is provided, the return value of the \`select\` function.
4041
- - If no \`select\` function is provided, an array of [\`RouteMatch\`](../RouteMatchType.md) objects.
4042
-
4043
- ## Examples
4044
-
4045
- \`\`\`tsx
4046
- import { useParentMatches } from '@tanstack/react-router'
4047
-
4048
- function Component() {
4049
- const parentMatches = useParentMatches()
4050
- // ^ [RouteMatch, RouteMatch, ...]
4051
- }
4052
- \`\`\`
4053
-
4054
- # useRouteContext hook
4055
-
4056
- The \`useRouteContext\` method is a hook that returns the current context for the current route. This hook is useful for accessing the current route context in a component.
4057
-
4058
- ## useRouteContext options
4059
-
4060
- The \`useRouteContext\` hook accepts an \`options\` object.
4061
-
4062
- ### \`opts.from\` option
4063
-
4064
- - Type: \`string\`
4065
- - Required
4066
- - The RouteID to match the route context from.
4067
-
4068
- ### \`opts.select\` option
4069
-
4070
- - Type: \`(context: RouteContext) => TSelected\`
4071
- - Optional
4072
- - If supplied, this function will be called with the route context object and the return value will be returned from \`useRouteContext\`.
4073
-
4074
- ## useRouteContext returns
4075
-
4076
- - The current context for the current route or \`TSelected\` if a \`select\` function is provided.
4077
-
4078
- ## Examples
4079
-
4080
- \`\`\`tsx
4081
- import { useRouteContext } from '@tanstack/react-router'
4082
-
4083
- function Component() {
4084
- const context = useRouteContext({ from: '/posts/$postId' })
4085
- // ^ RouteContext
4086
-
4087
- // OR
4088
-
4089
- const selected = useRouteContext({
4090
- from: '/posts/$postId',
4091
- select: (context) => context.postId,
4092
- })
4093
- // ^ string
4094
-
4095
- // ...
4096
- }
4097
- \`\`\`
4098
-
4099
- # useRouter hook
4100
-
4101
- The \`useRouter\` method is a hook that returns the current instance of [\`Router\`](../RouterType.md) from context. This hook is useful for accessing the router instance in a component.
4102
-
4103
- ## useRouter returns
4104
-
4105
- - The current [\`Router\`](../RouterType.md) instance.
4106
-
4107
- > ⚠️⚠️⚠️ **\`router.state\` is always up to date, but NOT REACTIVE. If you use \`router.state\` in a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use the [\`useRouterState\`](../useRouterStateHook.md) hook.**
4108
-
4109
- ## Examples
4110
-
4111
- \`\`\`tsx
4112
- import { useRouter } from '@tanstack/react-router'
4113
-
4114
- function Component() {
4115
- const router = useRouter()
4116
- // ^ Router
4117
-
4118
- // ...
4119
- }
4120
- \`\`\`
4121
-
4122
- # useRouterState hook
4123
-
4124
- The \`useRouterState\` method is a hook that returns the current internal state of the router. This hook is useful for accessing the current state of the router in a component.
4125
-
4126
- > [!TIP]
4127
- > If you want to access the current location or the current matches, you should try out the [\`useLocation\`](../useLocationHook.md) and [\`useMatches\`](../useMatchesHook.md) hooks first. These hooks are designed to be more ergonomic and easier to use than accessing the router state directly.
4128
-
4129
- ## useRouterState options
4130
-
4131
- The \`useRouterState\` hook accepts an optional \`options\` object.
4132
-
4133
- ### \`opts.select\` option
4134
-
4135
- - Type: \`(state: RouterState) => TSelected\`
4136
- - Optional
4137
- - If supplied, this function will be called with the [\`RouterState\`](../RouterStateType.md) object and the return value will be returned from \`useRouterState\`.
4138
-
4139
- ### \`opts.structuralSharing\` option
4140
-
4141
- - Type: \`boolean\`
4142
- - Optional
4143
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
4144
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
4145
-
4146
- ## useRouterState returns
4147
-
4148
- - The current [\`RouterState\`](../RouterStateType.md) object or \`TSelected\` if a \`select\` function is provided.
4149
-
4150
- ## Examples
4151
-
4152
- \`\`\`tsx
4153
- import { useRouterState } from '@tanstack/react-router'
4154
-
4155
- function Component() {
4156
- const state = useRouterState()
4157
- // ^ RouterState
4158
-
4159
- // OR
4160
-
4161
- const selected = useRouterState({
4162
- select: (state) => state.location,
4163
- })
4164
- // ^ ParsedLocation
4165
-
4166
- // ...
4167
- }
4168
- \`\`\`
4169
-
4170
- # useSearch hook
4171
-
4172
- The \`useSearch\` method is a hook that returns the current search query parameters as an object for the current location. This hook is useful for accessing the current search string and query parameters in a component.
4173
-
4174
- ## useSearch options
4175
-
4176
- The \`useSearch\` hook accepts an \`options\` object.
4177
-
4178
- ### \`opts.from\` option
4179
-
4180
- - Type: \`string\`
4181
- - Required
4182
- - The RouteID to match the search query parameters from.
4183
-
4184
- ### \`opts.shouldThrow\` option
4185
-
4186
- - Type: \`boolean\`
4187
- - Optional
4188
- - \`default: true\`
4189
- - If \`false\`,\`useSearch\` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return \`undefined\`.
4190
-
4191
- ### \`opts.select\` option
4192
-
4193
- - Type: \`(search: SelectedSearchSchema) => TSelected\`
4194
- - Optional
4195
- - If supplied, this function will be called with the search object and the return value will be returned from \`useSearch\`.
4196
-
4197
- ### \`opts.structuralSharing\` option
4198
-
4199
- - Type: \`boolean\`
4200
- - Optional
4201
- - Configures whether structural sharing is enabled for the value returned by \`select\`.
4202
- - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.
4203
-
4204
- ### \`opts.strict\` option
4205
-
4206
- - Type: \`boolean\`
4207
- - Optional - \`default: true\`
4208
- - If \`false\`, the \`opts.from\` option will be ignored and types will be loosened to \`Partial<FullSearchSchema>\` to reflect the shared types of all search query parameters.
4209
-
4210
- ## useSearch returns
4211
-
4212
- - If \`opts.from\` is provided, an object of the search query parameters for the current location or \`TSelected\` if a \`select\` function is provided.
4213
- - If \`opts.strict\` is \`false\`, an object of the search query parameters for the current location or \`TSelected\` if a \`select\` function is provided.
4214
-
4215
- ## Examples
4216
-
4217
- \`\`\`tsx
4218
- import { useSearch } from '@tanstack/react-router'
4219
-
4220
- function Component() {
4221
- const search = useSearch({ from: '/posts/$postId' })
4222
- // ^ FullSearchSchema
4223
-
4224
- // OR
4225
-
4226
- const selected = useSearch({
4227
- from: '/posts/$postId',
4228
- select: (search) => search.postView,
4229
- })
4230
- // ^ string
4231
-
4232
- // OR
4233
-
4234
- const looseSearch = useSearch({ strict: false })
4235
- // ^ Partial<FullSearchSchema>
4236
-
4237
- // ...
4238
- }
4239
- \`\`\`
4240
-
4241
- `;