useCookie
React hook to manage browser cookies with reactive callbacks, add, update, remove, and clear operations.
Demo
document.cookie: (empty)
Usage
Shorthand — key + optional callback:
Options form — key + options object:
Parameters
Signature
| Parameter | Type | Description |
|---|---|---|
key | string | The cookie key/name. |
optionsOrOnChange | ((value: T | null) => void) | UseCookieProps<T> | Optional. Callback or options object. |
Options (UseCookieProps<T>)
| Property | Type | Default | Description |
|---|---|---|---|
defaultValue | T | null | Value returned when cookie does not exist. |
path | string | '/' | Cookie path. |
domain | string | — | Cookie domain. |
expires | Date | number | string | — | Expiration date or days. |
maxAge | number | — | Max age in seconds. |
sameSite | 'strict' | 'lax' | 'none' | — | SameSite attribute policy. |
secure | boolean | — | Transmit only over HTTPS. |
partitioned | boolean | — | Partitioned cookie (CHIPS). |
serializer | Serializer<T> | JSON parse/stringify fallback | Custom serializer for non-string values. |
onChange | (value: T | null) => void | — | Called on every value change or update. |
onRemove | () => void | — | Called when cookie is removed via remove(). |
onRemoveAll | () => void | — | Called when all cookies are removed via removeAll(). |
Return Values
Returns a tuple [value, set, remove, removeAll]:
| Index | Type | Description |
|---|---|---|
value | T | null | Current cookie value. null when absent and no defaultValue is set. |
set | (value: T, options?: CookieAttributes) => void | Sets or updates the cookie, updates state, and fires onChange. |
remove | (options?: CookieAttributes) => void | Deletes the cookie, resets to defaultValue, and fires onRemove. |
removeAll | (options?: CookieAttributes) => void | Deletes all accessible cookies, resets to defaultValue, and fires onRemoveAll. |