- read

How to use SearchParams, the easy way — Next.js Shorts

Lukas Wimhofer 61

How to use SearchParams, the easy way — Next.js Shorts

Creating a custom hook to simplify working with SearchParams in Next.js.

Lukas Wimhofer
Level Up Coding
Published in
4 min read22 hours ago

--

I recently wanted to implement some filtering in my Next.js project using searchParams, and I must say, it started pretty clunky. Therefore, I have created a custom hook that abstracts all the clunkiness away and lets you update the searchParams in a straightforward and clean way. In this article, I am sharing the hook so you can focus on the important things in your projects.

The Problem

In Next.js, when managing URL search parameters (for filtering data,…), we usually interact with the native URLSearchParams. This can sometimes lead to repetitive code patterns, especially when adding, updating, or removing parameters.

The goal is to be able to add, update, or delete searchParams with something like this:

// Add or update search and remove title.

updateQueryString({ search: search }, ["title"]);

The Solution

To be able to manage searchParams as shown above we have to create 2 functions. The first one is createQueryString that takes in new params and the current searchParams, if any, and returns an updated query string. The second is useUpdateQueryString that uses the utility function above and the Next.js navigation hooks to facilitate the management of URL search parameters.

1. createQueryString

The createQueryString function is designed to generate a query string for URLs based on provided parameters.

function createQueryString(
params: Record<string, string | undefined>,
currentSearchParams?: URLSearchParams,
): string {
const newSearchParams = new URLSearchParams(
currentSearchParams?.toString() ?? "",
);

for (const [key, value] of Object.entries(params)) {
if (value === null) {
newSearchParams.delete(key);
} else {
newSearchParams.set(key, String(value));
}
}

return newSearchParams.toString();
}

Function flow of createQueryString :

  • A new URLSearchParams object, newSearchParams , is initialized. If currentSearchParams is provided, it initializes with those…