useQueryString
TheuseQueryString hook provides a convenient way to create and manipulate URL query strings. It takes the current URLSearchParams and returns a function to generate new query strings with updated parameters.
Installation
Import
Usage
Parameters
URLSearchParams
required
The current URL search parameters, typically obtained from Next.js
useSearchParams() or browser’s window.location.search.Returns
(params: QueryParams) => string
A memoized function that accepts an object of query parameters and returns a new query string. Parameters with
null values are removed from the query string.QueryParams Type
stringornumbervalues are added/updated in the query stringnullvalues remove the parameter from the query string
Type Definition
Examples
Product Filtering
Pagination
Search with Filters
Multi-Select Filters
Date Range Filter
Tab Navigation
Common Patterns
Preserving Existing Parameters
The hook automatically preserves existing parameters:Removing Parameters
Usenull to remove parameters:
Multiple Updates
Update multiple parameters at once:Reset All Filters
Use Cases
- Building search and filter interfaces
- Implementing pagination
- Managing tab navigation with URL state
- Creating shareable URLs with filter states
- Handling sort options
- Multi-select filters
- Date range selectors
- Any scenario requiring URL query parameter manipulation
Notes
- The hook is designed to work with Next.js App Router’s
useSearchParams - The
createQueryStringfunction is memoized and only recreates whensearchParamschanges - Numeric values are automatically converted to strings in the query string
- Setting a parameter to
nullremoves it from the query string - The hook preserves all existing parameters unless explicitly overridden or set to
null - The returned query string does not include the leading
?character - This hook does not modify the URL directly; you need to use it with a router or navigation method