useCookie

React hook to manage browser cookies with reactive callbacks, add, update, remove, and clear operations.

pnpm add react-callback-hooks

Demo

document.cookie: (empty)

Usage

Shorthand — key + optional callback:

import { useCookie } from 'react-callback-hooks'

const [auth, setAuth, removeAuth, removeAll] = useCookie<string>(
  'auth_token',
  (value) => console.log('auth changed to', value)
)

Options form — key + options object:

const [theme, setTheme, removeTheme, removeAll] = useCookie<'light' | 'dark'>(
  'app_theme',
  {
    defaultValue: 'light',
    path: '/',
    maxAge: 86400 * 30, // 30 days
    sameSite: 'lax',
    secure: true,
    onChange: (value) => console.log('theme changed to', value),
    onRemove: () => console.log('cookie removed'),
    onRemoveAll: () => console.log('all cookies removed')
  }
)

Parameters

Signature

useCookie<T>(key: string, onChange?: (value: T | null) => void)
useCookie<T>(key: string, options?: UseCookieProps<T>)
ParameterTypeDescription
keystringThe cookie key/name.
optionsOrOnChange((value: T | null) => void) | UseCookieProps<T>Optional. Callback or options object.

Options (UseCookieProps<T>)

PropertyTypeDefaultDescription
defaultValueTnullValue returned when cookie does not exist.
pathstring'/'Cookie path.
domainstringCookie domain.
expiresDate | number | stringExpiration date or days.
maxAgenumberMax age in seconds.
sameSite'strict' | 'lax' | 'none'SameSite attribute policy.
securebooleanTransmit only over HTTPS.
partitionedbooleanPartitioned cookie (CHIPS).
serializerSerializer<T>JSON parse/stringify fallbackCustom serializer for non-string values.
onChange(value: T | null) => voidCalled on every value change or update.
onRemove() => voidCalled when cookie is removed via remove().
onRemoveAll() => voidCalled when all cookies are removed via removeAll().

Return Values

Returns a tuple [value, set, remove, removeAll]:

IndexTypeDescription
valueT | nullCurrent cookie value. null when absent and no defaultValue is set.
set(value: T, options?: CookieAttributes) => voidSets or updates the cookie, updates state, and fires onChange.
remove(options?: CookieAttributes) => voidDeletes the cookie, resets to defaultValue, and fires onRemove.
removeAll(options?: CookieAttributes) => voidDeletes all accessible cookies, resets to defaultValue, and fires onRemoveAll.