|
| 1 | +import { useCallback, useEffect, useMemo, useRef } from "react" |
| 2 | +import { |
| 3 | + usePathname, |
| 4 | + useSearchParams as useNextSearchParams, |
| 5 | + useRouter |
| 6 | +} from "next/navigation" |
| 7 | + |
| 8 | +type SearchParamsSetterValue = |
| 9 | + | URLSearchParams |
| 10 | + | ((prevSearchParams: URLSearchParams) => URLSearchParams) |
| 11 | + |
| 12 | +type SetSearchParams = (newSearchParams: SearchParamsSetterValue) => void |
| 13 | + |
| 14 | +const useSearchParams = (): [URLSearchParams, SetSearchParams] => { |
| 15 | + const pathname = usePathname() |
| 16 | + const router = useRouter() |
| 17 | + const search = useNextSearchParams() |
| 18 | + |
| 19 | + /** |
| 20 | + * Keep track of whether navigate has been called in the current render cycle |
| 21 | + * to avoid adding extra entries in the history stack. |
| 22 | + */ |
| 23 | + const hasNavigatedRef = useRef(false) |
| 24 | + const searchParams = useMemo(() => new URLSearchParams(search), [search]) |
| 25 | + /** |
| 26 | + * Keep track of the current searchParams value so that updater functions can |
| 27 | + * use the current value rather than value from previous render. |
| 28 | + */ |
| 29 | + const searchParamsRef = useRef(searchParams) |
| 30 | + |
| 31 | + useEffect(() => { |
| 32 | + hasNavigatedRef.current = false |
| 33 | + /** |
| 34 | + * Each render, sync the ref with the current state value. |
| 35 | + * This is necessary in case search params has changed via some source other |
| 36 | + * than this hook (e.g., browser navigation). |
| 37 | + */ |
| 38 | + searchParamsRef.current = searchParams |
| 39 | + }) |
| 40 | + |
| 41 | + const setSearchParams: SetSearchParams = useCallback( |
| 42 | + nextValue => { |
| 43 | + const newParams = |
| 44 | + typeof nextValue === "function" ? |
| 45 | + nextValue(searchParamsRef.current) : |
| 46 | + nextValue |
| 47 | + |
| 48 | + searchParamsRef.current = newParams |
| 49 | + |
| 50 | + if (hasNavigatedRef.current) { |
| 51 | + router.replace(`${pathname}?${newParams}`) |
| 52 | + } else { |
| 53 | + router.push(`${pathname}?${newParams}`) |
| 54 | + } |
| 55 | + |
| 56 | + hasNavigatedRef.current = true |
| 57 | + }, |
| 58 | + [pathname, router] |
| 59 | + ) |
| 60 | + return [searchParams, setSearchParams] |
| 61 | +} |
| 62 | + |
| 63 | +export default useSearchParams |
0 commit comments