useUrlSearchParams

Tags:

A React Hook that helps to manage the URL search params.

There three mode in useUrlSearchParams:

  • history: like /path/to/page?a=1&b=2
  • hash: like /path/to/page#heading?a=1&b=2 (with ? in hash)
  • hash-params: like /path/to/page#/a=1&b=2 (without ? in hash)

Demo

Source
Params (history):
{"mode":"mode","val":["val"]}
Params (hash):
{}
Params (hash-params):
{}

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const [usp, setUsp, clearUsp] = useUrlSearchParams(mode, options)

Mode

export type UseUrlSearchParamsMode = 'history' | 'hash' | 'hash-params'

Options

export interface UseUrlSearchParamsOptions<T> { /** * Remove nullish values from the URLSearchParams * * @defaultValue true */ removeNullishValues?: boolean /** * Remove falsy values from the URLSearchParams * * @defaultValue false */ removeFalsyValues?: boolean /** * Initial value for the URLSearchParams * * @defaultValue {} */ initialValue?: T & Record<any, any> /** * Write back to `window.history` automatically * * @defaultValue true */ write?: boolean }

Returns

export type UseUrlSearchParamsReturns<T extends Record<string, any>> = [T, UseSetStateSetMergedState<T>, Noop]