Skip to content

useUrlSearchParam ​

Hook that provides reactive URLSearchParams for a single key

browser
test coverage
Last changed: 4 days ago

Installation ​

Library
CLI
Manual
typescript
import { useUrlSearchParam } from '@siberiacancode/reactuse';

Usage ​

typescript
const { value, set } = useUrlSearchParam('page', { initialValue: 1 });
// or
const { value, set } = useUrlSearchParam('page', 1);

Demo ​

Api ​

Parameters

NameTypeDefaultNote
keystring-The key of the url param
optionsUseUrlSearchParamOptions<Value> & { initialValue: Value }-The options object with required initialValue
options.initialValueValue-The initial value for the url param
options.mode?UrlSearchParamsMode'history'The mode to use for the URL ('history' | 'hash-params' | 'hash')
options.write?'push' | 'replace''replace'The mode to use for writing to the URL
options.serializer?(value: Value) => string-Custom serializer function to convert value to string
options.deserializer?(value: string) => Value-Custom deserializer function to convert string to value

Returns

UseUrlSearchParamReturn<Value>

Parameters

NameTypeDefaultNote
keystring-The key of the url param
initialValue?Value-The initial value for the url param

Returns

UseUrlSearchParamReturn<Value>

Type declaration ​

typescript
export type UrlSearchParamMode = 'hash-params' | 'hash' | 'history';

export interface UseUrlSearchParamOptions<Value> {
  /** The initial value of the search param */
  initialValue?: Value;
  /** The mode to use for writing to the URL */
  mode?: UrlSearchParamMode;
  /** The mode to use for writing to the URL */
  write?: 'push' | 'replace';
  /** The deserializer function to be invoked */
  deserializer?: (value: string) => Value;
  /** The serializer function to be invoked */
  serializer?: (value: Value) => string;
}

export interface UseUrlSearchParamsActionOptions {
  /** The mode to use for writing to the URL */
  write?: 'push' | 'replace';
}

export interface UseUrlSearchParamReturn<Value> {
  /** Current search param value */
  value: Value | undefined;
  /** Function to remove the search param */
  remove: (options?: UseUrlSearchParamsActionOptions) => void;
  /** Function to update search param */
  set: (value: Value, options?: UseUrlSearchParamsActionOptions) => void;
}

export interface UseUrlSearchParam {
  <Value>(
    key: string,
    options: UseUrlSearchParamOptions<Value> & { initialValue: Value }
  ): UseUrlSearchParamReturn<Value>;

  <Value>(
    key: string,
    options?: UseUrlSearchParamOptions<Value>
  ): UseUrlSearchParamReturn<Value | undefined>;

  <Value>(key: string, initialValue: Value): UseUrlSearchParamReturn<Value>;

  <Value>(key: string): UseUrlSearchParamReturn<Value | undefined>;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
B
babin
babin

Released under the MIT License.