@@ -2,35 +2,25 @@ import { last } from '@tanstack/router-core'
22import { useCallback , useEffect , useState } from 'react'
33import { useRouter } from './useRouter'
44import { useMatch } from './useMatch'
5- import type { AnyRouteMatch , ParsedLocation } from '@tanstack/router-core'
5+ import { useRouterState } from './useRouterState'
6+ import type { ParsedLocation } from '@tanstack/router-core'
67
7- export type UseLocationResult = {
8- activeLocationMatch : AnyRouteMatch | undefined
8+ export type UseActiveLocationResult = {
9+ activeLocation : ParsedLocation
910 getFromPath : ( from ?: string ) => string
11+ setActiveLocation : ( location ?: ParsedLocation ) => void
1012}
1113
12- export const useActiveLocation = ( location ?: ParsedLocation ) => {
13- const { matchRoutes, state } = useRouter ( )
14- const [ activeLocation , setActiveLocation ] = useState < ParsedLocation > (
15- location ?? state . location ,
16- )
17- const [ customActiveLocation , _setCustomActiveLocation ] =
18- useState < ParsedLocation > ( location ?? state . location )
19- const [ useCustomActiveLocation , setUseCustomActiveLocation ] =
20- useState ( ! ! location )
14+ export const useActiveLocation = ( location ?: ParsedLocation ) : UseActiveLocationResult => {
15+ const router = useRouter ( )
16+ const routerLocation = useRouterState ( { select : ( state ) => state . location } )
17+ const [ activeLocation , setActiveLocation ] = useState < ParsedLocation > ( location ?? routerLocation )
18+ const [ customActiveLocation , setCustomActiveLocation ] = useState < ParsedLocation | undefined > ( location )
2119
2220 useEffect ( ( ) => {
23- if ( ! useCustomActiveLocation ) {
24- setActiveLocation ( state . location )
25- } else {
26- setActiveLocation ( customActiveLocation )
27- }
28- } , [ state . location , useCustomActiveLocation , customActiveLocation ] )
29-
30- const setCustomActiveLocation = ( location : ParsedLocation ) => {
31- _setCustomActiveLocation ( location )
32- setUseCustomActiveLocation ( true )
33- }
21+ setActiveLocation ( customActiveLocation ?? routerLocation )
22+ } , [ routerLocation , customActiveLocation ] )
23+
3424
3525 const currentRouteMatch = useMatch ( {
3626 strict : false ,
@@ -39,15 +29,15 @@ export const useActiveLocation = (location?: ParsedLocation) => {
3929
4030 const getFromPath = useCallback (
4131 ( from ?: string ) => {
42- const activeLocationMatches = matchRoutes ( activeLocation , {
32+ const activeLocationMatches = router . matchRoutes ( activeLocation , {
4333 _buildLocation : false ,
4434 } )
4535
4636 const activeLocationMatch = last ( activeLocationMatches )
4737
4838 return from ?? activeLocationMatch ?. fullPath ?? currentRouteMatch . fullPath
4939 } ,
50- [ activeLocation , currentRouteMatch . fullPath , matchRoutes ] ,
40+ [ activeLocation , currentRouteMatch . fullPath , router ] ,
5141 )
5242
5343 return {
0 commit comments