npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

use-search-query-params

v0.2.0

Published

Typed React hook for URL search parameters — generic over an interface, with a ts-patch transformer that fills the runtime schema.

Readme

use-search-query-params

Типизированный React-хук для URL search-параметров — дженерик по интерфейсу, с ts-patch-трансформером, который подставляет рантайм-схему из T.

interface ProductSearchParams {
  query?: string;
  page: number;
  sort: "relevance" | "price" | "rating";
  tags: string[];
}

function ProductList() {
  const { fields, set, update, clear, get } =
    useSearchQueryParams<ProductSearchParams>();

  // fields.page  -> number | undefined
  // fields.sort  -> "relevance" | "price" | "rating" | undefined
  // fields.tags  -> string[] | undefined

  return <button onClick={() => set("page", (fields.page ?? 0) + 1)}>Next</button>;
}

Никакого рантайм-аргумента — трансформер подставляет схему из T на этапе компиляции. Подходит для приложений на react-router-dom (хук поверх useSearchParams) и tsc / ts-patch.

Установка

npm install use-search-query-params
npm install -D ts-patch

Peer-зависимости: react >=18, react-router-dom >=6.

Настройка трансформера

Добавьте в tsconfig.json приложения:

{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "use-search-query-params/transformer",
        "type": "program"
      }
    ]
  }
}

Собирайте проект через tspc (обёртка над tsc, которую ставит ts-patch) вместо tsc. Альтернатива — однократный ts-patch install, патчит локальный tsc в node_modules.

Vite/esbuild/swc не запускают ts-трансформеры. Эта библиотека рассчитана на сборку через tsc/tspc. Без трансформера вызов остаётся useSearchQueryParams<T>() без аргумента — хук выводит предупреждение и декодирует все параметры как строки.

API

useSearchQueryParams<T>() возвращает объект:

| Поле | Тип | Поведение | |------|-----|-----------| | fields | { [K in keyof T]: T[K] \| undefined } | Декодированные значения; отсутствующие или невалидные — undefined. | | get(key) | string \| null | Сырое чтение через URLSearchParams.get. | | set(key, value) | void | value: string \| number \| undefined; пустая строка/undefined удаляют ключ. | | update(partial) | void | Частичное обновление нескольких ключей сразу. | | remove(key) | void | Удаляет ключ. | | clear() | void | Удаляет все search-параметры. |

Ключи set / update / remove / get ограничены keyof T. Значения set / update сохранены свободно типизированными (string | number | undefined), как в исходном паттерне хука.

Дженерик опционален. Без <T> параметр получает дефолт Record<string, string>: fields становится словарём { [key: string]: string | undefined }, аксессоры принимают любой строковый ключ, fallback в хуке декодирует всё как строки.

const { fields, set } = useSearchQueryParams();
// fields["foo"]: string | undefined
set("foo", "bar");

Что трансформер умеет вывести из T

| TS-тип в T[K] | Рантайм-описание | |-----------------|------------------| | number / string / boolean | шорткат ("number", "string", "boolean") | | Date | "date" | | "a" \| "b" | { type: "string", enum: ["a", "b"] } | | 1 \| 2 \| 3 | { type: "number", enum: [1, 2, 3] } | | string[], Array<T> | { type, array: true } | | T \| undefined, T? | то же, что T (URL-параметр и так может отсутствовать) | | Неизвестное | "string" (URL-параметры всегда строки) |

Тип резолвится через type checker — алиасы, импорты из других модулей, intersection, mapped types выводятся автоматически.

Эскейп-хатч: ручная схема

Если файл собирается без трансформера, схему можно передать вторым аргументом:

useSearchQueryParams<ProductSearchParams>({
  query: "string",
  page: "number",
  sort: { type: "string", enum: ["relevance", "price", "rating"] },
  tags: { type: "string", array: true },
});

Эта же сигнатура используется в тестах библиотеки.

Пример

В репозитории — папка example/, компилируемая через tspc. После npm run build:example посмотрите example/dist/main.js: вызов useSearchQueryParams() получит подставленный объект-схему, выведенный из FilterParams.

Лицензия

MIT