UseCookie
guarahooks/use-cookieFreeHook
Synchronizes a value with cookies.
Install it
npx shadcn@latest add https://guarahooks.com/r/use-cookie.jsonSource
1import { useCallback, useMemo } from 'react';23export type CookieOptions = {4 path?: string;5 expires?: Date | string;6 maxAge?: number;7 domain?: string;8 secure?: boolean;9 sameSite?: 'strict' | 'lax' | 'none';10};1112/**13 * Type-safe React hook for managing cookies.14 * Provides methods to get, set, and remove cookies.15 *16 * @param key The cookie key17 * @param initialValue Optional initial value for the cookie18 * @returns [value, setCookie, removeCookie]19 */20export function useCookie<T = string>(21 key: string,22 initialValue?: T,23): [T | undefined, (value: T, options?: CookieOptions) => void, () => void] {24 // Helper to check if running in browser25 const isBrowser = typeof document !== 'undefined';2627 // Parse cookie string to object28 const getCookies = useCallback((): Record<string, string> => {29 if (!isBrowser) return {};30 return document.cookie.split('; ').reduce(31 (acc, cookie) => {32 const [k, ...v] = cookie.split('=');33 acc[decodeURIComponent(k)] = decodeURIComponent(v.join('='));34 return acc;35 },36 {} as Record<string, string>,37 );38 }, [isBrowser]);3940 // Set cookie41 const setCookie = useCallback(42 (val: T | undefined, options: CookieOptions = {}) => {43 if (!isBrowser) return;44 let encodedValue: string;45 if (typeof val === 'string') {46 encodedValue = encodeURIComponent(val);47 } else {48 encodedValue = encodeURIComponent(JSON.stringify(val));49 }50 let cookieStr = `${encodeURIComponent(key)}=${encodedValue}`;51 if (options.path) cookieStr += `; path=${options.path}`;52 if (options.expires)53 cookieStr += `; expires=${options.expires instanceof Date ? options.expires.toUTCString() : options.expires}`;54 if (options.maxAge) cookieStr += `; max-age=${options.maxAge}`;55 if (options.domain) cookieStr += `; domain=${options.domain}`;56 if (options.secure) cookieStr += '; secure';57 if (options.sameSite) cookieStr += `; samesite=${options.sameSite}`;58 document.cookie = cookieStr;59 },60 [isBrowser, key],61 );6263 // Remove cookie64 const removeCookie = useCallback(() => {65 setCookie(undefined, { path: '/', expires: new Date(0) });66 }, [setCookie]);6768 // Get cookie value (and create if missing)69 const value = useMemo(() => {70 const cookies = getCookies();71 if (!(key in cookies)) {72 if (initialValue !== undefined) {73 setCookie(initialValue);74 return initialValue;75 } else {76// … truncated
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCopyToClipboarduse-copy-to-clipboard | guarahooks | Hooks | Free | no deps |
