Next.js Discord

Discord Forum

Nextjs - custom hook with useSearchParams & usePathname & useRouter is sending rsc requests

Answered
Laysan Albatross posted this in #help-forum
Open in Discord
Laysan AlbatrossOP
Hello,

I wrote custom hook which is using useSearchParams, usePathname, useRouter to simplify storing state in url.
I am using this custom hook inside client compontent ("use client").

export function useSearchName(): [string, (value: string) => void] {
    const [value, setValue] = useSearchParamByString(
        "search-name",
        "",
    );

    return [value, setValue];
}

function useSearchParamByString(
    key: string,
    defaultValue: string,
): [string, (value: string) => void] {
    const searchParams = useSearchParams();
    const pathname = usePathname();
    const router = useRouter();

    const setSearchParam = (value: string) => {
        const params = new URLSearchParams(searchParams);
        params.set(key, value);

        router.replace(`${pathname}?${params.toString()}`);
    };

    const searchParamValue = searchParams.get(key);

    if (searchParamValue !== null) {
        return [searchParamValue, setSearchParam];
    }

    return [defaultValue, setSearchParam];
}


I noticed that in network tab I can see rsc requests which means this is server component even when I am using it in client component?
I don't understand this behaviour.

Could someone explain me what I am doing wrong? I don't want to trigger rsc requests.
"next": "14.2.4"
source code: https://github.com/Freemantle01/nextjs-search-params-issue/blob/main/src/app/page.tsx

6 Replies

@Laysan Albatross can you plz try to add { shallow: true } in your code where you replace the router?
router.replace(`${pathname}?${params.toString()}`, undefined, { shallow: true });
I am not that sure but give it a try!
Laysan AlbatrossOP
@James4u
there is no such property as shallow

replace(href: string, options?: NavigateOptions): void;

where NaviagateOptions is:
export interface NavigateOptions {
    scroll?: boolean;
}
Answer
Laysan AlbatrossOP
thanks for help,
with window.history.pushState or window.history.replaceState it doesn't sends rsc requests