Skip to main content
Version: Next (Unreleased)

useQueryParams

Read and write URL query parameters with full type safety. Automatically stays in sync with browser navigation (back / forward).

Signature​

function useQueryParams<TQuery extends Record<string, any>>(): {
get: (...keys: (keyof TQuery)[]) => Partial<TQuery>;
set: (params: Partial<TQuery>, url?: string) => void;
build: (params: Partial<TQuery>) => string;
pathname: string;
search: string;
clear: () => void;
}

Type parameter​

Define your query shape as a generic for auto-completion and type-safe access:

interface Filters {
page: number;
q: string;
active: boolean;
}

const { get, set } = useQueryParams<Filters>();
const { page, q } = get("page", "q");
set({ page: 2 });

Return value​

Method / PropertyDescription
get(...keys)Returns an object with the requested params, auto-casting to boolean, number, or parsed JSON
set(params, url?)Replaces the whole query string with params (history.replaceState). Keeps the hash. Optionally target a different path. set({}) removes the query string
build(params)Returns a query string from params without navigating. Skips null/undefined, serializes objects and arrays as JSON
pathnameCurrent location.pathname
searchCurrent location.search
clear()Removes all query params from the URL, keeping the hash

pathname and search are reactive. Every component using the hook re-renders after set, clear, or browser back/forward navigation.

Value auto-casting​

get() automatically casts values from the URL string:

String valueCasted as
"true" / "false"boolean
"null"null
"42", "-1.5"number
'{"a":1}', "[1,2]"Parsed object/array
"007", "0x10", "1e5", unsafe integersstring (kept as-is)
Anything elsestring

Example​

import { useQueryParams } from "@julianfere/hooked";

interface SearchParams {
q: string;
page: number;
active: boolean;
}

function SearchPage() {
const { get, set, clear } = useQueryParams<SearchParams>();
const { q = "", page = 1 } = get("q", "page");

return (
<div>
<input value={q} onChange={(e) => set({ q: e.target.value, page: 1 })} />
{/* set() replaces the query string, so keep the params you need */}
<button onClick={() => set({ q, page: page + 1 })}>Next page</button>
<button onClick={clear}>Clear filters</button>
</div>
);
}
note

During server rendering pathname and search are empty strings. get, set and clear use window, so call them only on the client (in event handlers or effects).