498

useCookie

Hook that manages cookie value

statemediumtest coverage
import { getCookie, useCookie } from '@siberiacancode/reactuse';
import { MoonIcon, SunIcon } from 'lucide-react';

type Theme = 'dark' | 'light';

const getInitialTheme = (): Theme => {
  if (typeof window === 'undefined') return 'dark';
  const cookieTheme = getCookie('reactuse_docs_theme') as Theme | undefined;
  if (cookieTheme === 'dark' || cookieTheme === 'light') return cookieTheme;
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};

const Demo = () => {
  const themeCookie = useCookie<Theme>('reactuse_docs_theme', {
    initialValue: getInitialTheme,
    path: '/'
  });

  const onToggle = () => {
    const nextTheme = themeCookie.value === 'dark' ? 'light' : 'dark';
    themeCookie.set(nextTheme, { path: '/' });
    const root = document.documentElement;
    root.classList.remove('light', 'dark');
    root.classList.add(themeCookie.value);
  };

  return (
    <section className='flex w-full max-w-sm flex-col items-center gap-3 p-8'>
      <button
        aria-label='Toggle theme'
        className='rounded-full!'
        data-size='icon'
        data-variant='outline'
        type='button'
        onClick={onToggle}
      >
        {themeCookie.value === 'dark' && <MoonIcon className='text-foreground size-5' />}
        {themeCookie.value === 'light' && <SunIcon className='text-foreground size-5' />}
      </button>
    </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