Skip to content

Commit c1ac43b

Browse files
committed
fix: Init the optimistic search params from URL
Looks like the useSearchParams defaultInit value is cached in RR core, and is not evaluated on subsequent mounts.
1 parent 7bec121 commit c1ac43b

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

packages/nuqs/src/adapters/lib/react-router.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,23 @@ export function createReactRouterBasedAdapter(
7878
}
7979
function useOptimisticSearchParams() {
8080
const [serverSearchParams] = useSearchParams(
81+
// Note: this will only be taken into account the first time the hook is called,
82+
// and cached for subsequent calls, causing problems when mounting components
83+
// after shallow updates have occurred.
8184
typeof location === 'undefined'
8285
? new URLSearchParams()
8386
: new URLSearchParams(location.search)
8487
)
85-
const [searchParams, setSearchParams] = useState(serverSearchParams)
88+
const [searchParams, setSearchParams] = useState(() => {
89+
if (typeof location === 'undefined') {
90+
// We use this on the server to SSR with the correct search params.
91+
return serverSearchParams
92+
}
93+
// Since useSearchParams isn't reactive to shallow changes,
94+
// it doesn't pick up changes in the URL on mount, so we need to initialise
95+
// the reactive state with the current URL instead.
96+
return new URLSearchParams(location.search)
97+
})
8698
useEffect(() => {
8799
function onPopState() {
88100
setSearchParams(new URLSearchParams(location.search))

0 commit comments

Comments
 (0)