Skip to content

useCookie ​

Hook that manages cookie value

browser
test coverage
Last changed: 5 days ago

Installation ​

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

Usage ​

typescript
const { value, set, remove } = useCookie('key', 'value');

Demo ​

Api ​

Parameters

NameTypeDefaultNote
keystring-The key of the cookie
initialValue?UseCookieInitialValue<Value>-The initial value of the cookie

Returns

UseCookieReturn<Value>

Parameters

NameTypeDefaultNote
keystring-The key of the cookie
optionsUseCookieOptions<Value>-The options object
options.initialValue?UseCookieInitialValue<Value>-The initial value of the cookie
options.deserializer?(value: string) => Value-The deserializer function to be invoked
options.serializer?(value: Value) => string-The serializer function to be invoked

Returns

UseCookieReturn<Value | undefined>

Type declaration ​

typescript
export interface RemoveCookieParams {
  domain?: string;
  expires?: Date;
  maxAge?: number;
  path?: string;
  sameSite?: 'Lax' | 'None' | 'Strict';
  secure?: boolean;
}

export interface SetCookieParams {
  domain?: string;
  expires?: Date;
  httpOnly?: boolean;
  maxAge?: number;
  path?: string;
  sameSite?: 'Lax' | 'None' | 'Strict';
  secure?: boolean;
}

export type UseCookieInitialValue<Value> = (() => Value) | Value;

export interface UseCookieOptions<Value> {
  /* The domain of the cookie */
  domain?: string;
  /* The expiration date of the cookie */
  expires?: Date;
  /* Whether the cookie is httpOnly */
  httpOnly?: boolean;
  /* The initial value of the storage */
  initialValue?: UseCookieInitialValue<Value>;
  /* The maximum age of the cookie */
  maxAge?: number;
  /* The path of the cookie */
  path?: string;
  /* The sameSite of the cookie */
  sameSite?: 'Lax' | 'None' | 'Strict';
  /* Whether the cookie is secure */
  secure?: boolean;
  /* The deserializer function to be invoked */
  deserializer?: (value: string) => Value;
  /* The serializer function to be invoked */
  serializer?: (value: Value) => string;
}

export interface UseCookieReturn<Value> {
  /* The value of the cookie */
  value: Value;
  /* The remove function */
  remove: (options?: RemoveCookieParams) => void;
  /* The set function */
  set: (value: Value, options?: SetCookieParams) => void;
}

export interface UseCookie {
  <Value>(
    key: string,
    options: UseCookieOptions<Value> & {
      initialValue: UseCookieInitialValue<Value>;
    }
  ): UseCookieReturn<Value>;

  <Value>(key: string, options?: UseCookieOptions<Value>): UseCookieReturn<Value | undefined>;

  <Value>(key: string, initialValue: UseCookieInitialValue<Value>): UseCookieReturn<Value>;

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

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
B
babin
babin

Released under the MIT License.