475

useCookie

Hook that manages cookie value

statemediumtest coverage
Email notificationsHow often you get updates

Saved as notify=daily cookie.

import { useCookie } from '@siberiacancode/reactuse';
import { BellIcon, ChevronDownIcon } from 'lucide-react';

const FREQUENCY_OPTIONS = [
  { value: 'live', label: 'Real-time' },
  { value: 'daily', label: 'Daily digest' },
  { value: 'weekly', label: 'Weekly summary' },
  { value: 'off', label: 'Off' }
];

const Demo = () => {
  const cookie = useCookie('notify', 'daily');

  return (
    <section className='flex min-w-md flex-col gap-2 p-4'>
      <div className='flex w-full max-w-md items-start justify-between gap-4 rounded-xl border p-4'>
        <div className='flex items-center gap-3'>
          <BellIcon className='text-muted-foreground size-6 shrink-0' />
          <div className='flex flex-col gap-0.5'>
            <span className='text-sm font-medium'>Email notifications</span>
            <span className='text-muted-foreground text-xs'>How often you get updates</span>
          </div>
        </div>

        <div className='relative'>
          <select
            value={cookie.value ?? 'daily'}
            onChange={(event) => cookie.set(event.target.value)}
          >
            {FREQUENCY_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <ChevronDownIcon className='text-muted-foreground pointer-events-none absolute top-1/2 right-2 size-4 -translate-y-1/2' />
        </div>
      </div>

      <p className='text-muted-foreground text-xs'>
        Saved as <code>notify={cookie.value ?? 'daily'}</code> cookie.
      </p>
    </section>
  );
};

export default Demo;

Installation

pnpm add @siberiacancode/reactuse

Usage

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

Type Declarations

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>;
}

API

Parameters

NameTypeDefaultNote
keystring-The key of the cookie
initialValueUseCookieInitialValue<Value>-The initial value of the cookie

Returns

UseCookieReturn<Value>

Parameters

NameTypeDefaultNote
keystring-The key of the cookie
optionsUseCookieOptions<Value>-The options object
options.initialValueUseCookieInitialValue<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>

Contributors

ddebabinbbabin

Last updated on