1
1
import { safelyRunOnBrowser } from 'instantsearch.js/es/lib/utils' ;
2
2
import { headers } from 'next/headers' ;
3
- import { usePathname } from 'next/navigation' ;
4
- import React , { useEffect , useRef } from 'react' ;
3
+ import React , { useEffect , useMemo , useRef } from 'react' ;
5
4
import {
6
5
InstantSearch ,
7
6
InstantSearchRSCContext ,
@@ -21,11 +20,9 @@ import type {
21
20
} from 'react-instantsearch-core' ;
22
21
23
22
const InstantSearchInitialResults = Symbol . for ( 'InstantSearchInitialResults' ) ;
24
- const InstantSearchLastPath = Symbol . for ( 'InstantSearchLastPath' ) ;
25
23
declare global {
26
24
interface Window {
27
25
[ InstantSearchInitialResults ] ?: InitialResults ;
28
- [ InstantSearchLastPath ] ?: string ;
29
26
}
30
27
}
31
28
@@ -51,11 +48,17 @@ export function InstantSearchNext<
51
48
} : InstantSearchNextProps < TUiState , TRouteState > ) {
52
49
const isMounting = useRef ( true ) ;
53
50
const isServer = typeof window === 'undefined' ;
54
- const pathname = usePathname ( ) ;
55
- const hasRouteChanged =
56
- ! isServer &&
57
- window [ InstantSearchLastPath ] &&
58
- window [ InstantSearchLastPath ] !== pathname ;
51
+
52
+ const hasRouteChanged = useMemo ( ( ) => {
53
+ // On server, always return false
54
+ if ( isServer ) {
55
+ return false ;
56
+ }
57
+
58
+ // On client, route has changed if initialResults have been cleaned up
59
+ const hasInitialResults = window [ InstantSearchInitialResults ] !== undefined ;
60
+ return ! hasInitialResults ;
61
+ } , [ isServer ] ) ;
59
62
60
63
// We only want to trigger a search from a server environment
61
64
// or if a Next.js route change has happened on the client
@@ -69,10 +72,6 @@ export function InstantSearchNext<
69
72
} ;
70
73
} , [ ] ) ;
71
74
72
- useEffect ( ( ) => {
73
- window [ InstantSearchLastPath ] = pathname ;
74
- } , [ pathname ] ) ;
75
-
76
75
const nonce = safelyRunOnBrowser ( ( ) => undefined , {
77
76
fallback : ( ) => headers ( ) . get ( 'x-nonce' ) || undefined ,
78
77
} ) ;
0 commit comments