Skip to content

Commit

Permalink
chore: Fix useEffect loop due to referential inconsistency of default…
Browse files Browse the repository at this point in the history
… value
  • Loading branch information
franky47 committed Oct 7, 2024
1 parent 670f15a commit 0c68be7
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/nuqs/src/useQueryStates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ export type UseQueryStatesReturn<T extends UseQueryStatesKeysMap> = [
SetValues<T>
]

// Ensure referential consistency for the default value of urlKeys
// by hoisting it out of the function scope.
// Otherwise useEffect loops go brrrr
const defaultUrlKeys = {}

/**
* Synchronise multiple query string arguments to React state in Next.js
*
Expand All @@ -66,7 +71,7 @@ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
throttleMs = FLUSH_RATE_LIMIT_MS,
clearOnDefault = false,
startTransition,
urlKeys = {}
urlKeys = defaultUrlKeys
}: Partial<
UseQueryStatesOptions & {
// todo: Move into UseQueryStatesOptions in v2 (requires a breaking change
Expand Down Expand Up @@ -110,7 +115,7 @@ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
)
setInternalState(state)
}, [
Object.keys(keyMap)
Object.keys(urlKeys)
.map(key => initialSearchParams?.get(key))
.join('&'),
stateKeys,
Expand Down

0 comments on commit 0c68be7

Please sign in to comment.