At the time of writing, I don't know if this is the optimal way, but after some trial and error, I got it working.

This example demonstrates a hook that gives you the current value of the ?view=... (or a default) and a function you can call to change it so that ?view=before becomes ?view=after.

In NextJS v13 with the pages directory:


import { useRouter } from "next/router";

export function useNamesView() {
    const KEY = "view";
    const DEFAULT_NAMES_VIEW = "buttons";
    const router = useRouter();

    let namesView: Options = DEFAULT_NAMES_VIEW;
    const raw = router.query[KEY];
    const value = Array.isArray(raw) ? raw[0] : raw;
    if (value === "buttons" || value === "table") {
        namesView = value;
    }

    function setNamesView(value: Options) {
        const [asPathRoot, asPathQuery = ""] = router.asPath.split("?");
        const params = new URLSearchParams(asPathQuery);
        params.set(KEY, value);
        const asPath = `${asPathRoot}?${params.toString()}`;
        router.replace(asPath, asPath, { shallow: true });
    }

    return { namesView, setNamesView };
}

In NextJS v13 with the app directory.


import { useRouter, useSearchParams, usePathname } from "next/navigation";

type Options = "buttons" | "table";

export function useNamesView() {
    const KEY = "view";
    const DEFAULT_NAMES_VIEW = "buttons";
    const router = useRouter();
    const searchParams = useSearchParams();
    const pathname = usePathname();

    let namesView: Options = DEFAULT_NAMES_VIEW;
    const value = searchParams.get(KEY);
    if (value === "buttons" || value === "table") {
        namesView = value;
    }

    function setNamesView(value: Options) {
        const params = new URLSearchParams(searchParams);
        params.set(KEY, value);
        router.replace(`${pathname}?${params}`);
    }

    return { namesView, setNamesView };
}

The trick is that you only want to change 1 query string value and respect whatever was there before. So if the existing URL was /page?foo=bar and you want that to become /page?foo=bar&and=also you have to consume the existing query string and you do that with:


const searchParams = useSearchParams();
...
const params = new URLSearchParams(searchParams);
params.set('and', 'also')

Comments

Fahad

Thanks man! that really helped me

Rafael Pessoa

After setting url param, use push function from useRouter.

Mhamad Raad

thanks fam, this still does not exist in the documentation, and it has been forever since the update, great job, thank you, you spared me a couple of hours of figuring it out myself.

Sina

This is the exact thing I was looking for.
Thanks

Your email will never ever be published.

Previous:
How much faster is Cheerio at parsing depending on xmlMode? December 5, 2022 Node, JavaScript
Next:
Pip-Outdated.py - a script to compare requirements.in with the output of pip list --outdated December 22, 2022 Python
Related by category:
How to SSG a Vite SPA April 26, 2025 JavaScript, React
Switching from Next.js to Vite + wouter July 28, 2023 JavaScript, React
An ideal pattern to combine React Router with TanStack Query November 18, 2024 JavaScript, React
get in JavaScript is the same as property in Python February 13, 2025 JavaScript
Related by keyword:
Switching from Next.js to Vite + wouter July 28, 2023 Node, React, JavaScript
Notes on porting a Next.js v14 app from Pages to App Router March 2, 2024 React, JavaScript
Programmatically render a NextJS page without a server in Node September 6, 2022 Web development, Node, JavaScript
Make your NextJS site 10-100x faster with Express caching February 18, 2022 Node, Nginx, React, JavaScript