smolter
API

useSearchParams

Read the current query string and replace it through navigation.

Compatibility

ReactAvailable in this renderer's browser integration.
React SSRAvailable to this renderer's SSR integration; browser event handlers run after hydration.
PreactAvailable in this renderer's browser integration.
Preact SSRAvailable to this renderer's SSR integration; browser event handlers run after hydration.

Import from @kasperrt/smolter/react @kasperrt/smolter/preact

Signature

function useSearchParams(): [
  URLSearchParams,
  (
    value: URLSearchParams | Record<string, string>,
    options?: NavigateOptions,
  ) => void,
];

Parameters

The hook takes no arguments. The setter accepts URLSearchParams or Record<string, string>, followed by optional NavigateOptions. It does not accept a callback updater.

Returns

Returns [params, setParams]. params is memoized from the current URL search string. Changing that object does not navigate; call setParams explicitly. The setter replaces the query string and omits the previous hash.

Preserving other fields

Clone the current parameters before changing a field. Use URLSearchParams for repeated keys; an ordinary record supports one value per key.

import { useSearchParams } from "@kasperrt/smolter/preact";

export function SortControl() {
  const [params, setParams] = useSearchParams();

  function sortByName() {
    const next = new URLSearchParams(params);
    next.set("sort", "name");
    setParams(next, { replace: true });
  }

  return <button onClick={sortByName}>Sort by name</button>;
}

Loading and revalidation

Setting parameters performs navigation to the current pathname, so the active loader may run. shouldRevalidate receives the old and new URLs and can decline that reload. Use a GET fetcher form when search results should be independent of the browser address.

View implementation ↗