How to Implement a Custom useQueryParams Hook for Next.js App

Samir Mirzaliyev
2 min readOct 3, 2024

Managing query parameters is often necessary in modern web applications, particularly when dealing with dynamic data. In Next.js, you can efficiently handle query parameters using a custom hook that simplifies URL manipulation. This article will walk you through creating a useQueryParams hook for use in Next.js applications, ensuring strong type safety by utilizing the next/navigation module introduced in Next.js 13.

export const useQueryParams = <
T extends Record<string, string | number | boolean | unknown>,
>() => {
const searchParams = useSearchParams();
const router = useRouter();

// Memoize the query parameters to avoid recomputation on each render
const queryParam = useMemo(() => {
const query = new URLSearchParams();
searchParams.forEach((value, key) => {
query.append(key, value);
});
return query;
}, [searchParams]);

// Set a new query parameter or update an existing one
const setQueryParam = <K extends keyof T>(name: K, value: T[K]) => {
queryParam.set(String(name), String(value));
router.replace(`?${queryParam}`, { scroll: false });
};

// Get the value of a specific query parameter
const getQueryParam = <K extends keyof T>(name: K): T[K] | undefined => {
const value = queryParam.get(String(name));
if (value === null) return undefined;

return value as T[K];
};

return {
queryParam,
setQueryParam,
getQueryParam,
};
};
  • Generics for Type Safety:
    The hook is typed with a generic <T> which extends Record<string, string | number | boolean | unknown>. This ensures that the query parameters we are dealing with can be of type string, number, boolean, or any other type you want to handle.
  • Memoization of Query Parameters:
    useMemo ensures that the queryParam object is only recomputed when the searchParams change, avoiding unnecessary recomputations on each render.
  • Setting Query Parameters:
    The setQueryParam function allows you to either set a new query parameter or update an existing one. After modifying the parameters, it uses router.push to update the URL without reloading the page.
  • Getting Query Parameters:
    The getQueryParam function fetches the value of a specific query parameter, returning undefined if the parameter is not present.

With this hook, you can easily manage and reuse the query parameters in any Next.js project. I hope this will be helpful to you. See you in the next article.

--

--

Samir Mirzaliyev
Samir Mirzaliyev

No responses yet