Skip to content

useCookie

Saurav-TB-Pandey edited this page Aug 10, 2026 · 1 revision

useCookie

Synchronize state with browser cookies. Strictly string-based and completely hydration-safe for Server-Side Rendering (SSR). It cleanly separates initial renders from client reconciliation and supports all native cookie attributes.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation, managing a string cookie with no special attributes or SSR fallbacks.

import { useCookie } from "react-hook-lab";

function BasicCookie() {
  const [theme, setTheme] = useCookie("theme");

  return (
    <div>
      <p>Current theme: {theme ?? "None"}</p>
      <button onClick={() => setTheme("dark")}>Set Dark</button>
      <button onClick={() => setTheme("light")}>Set Light</button>
    </div>
  );
}

Common (Standard Usage)

Handling an initial SSR fallback value and setting expiration defaults.

import { useCookie } from "react-hook-lab";

function ConsentBanner() {
  // Pass an options object with your initial SSR/fallback value
  const [consentStr, setCookie, deleteCookie] = useCookie("cookie_consent", { 
    initialValue: "false",
    days: 365 // Default expiration when updating the cookie
  });
  
  if (consentStr === "true") return null;

  return (
    <div className="banner">
      <p>We use cookies to improve your experience.</p>
      <button onClick={() => setCookie("true")}>Accept</button>
      <button onClick={() => deleteCookie()}>Reject</button>
    </div>
  );
}

Advanced (All Parameters)

An exhaustive example overriding cookie options at set-time (e.g. secure, sameSite, and path).

import { useCookie } from "react-hook-lab";

function AdvancedCookie() {
  const [session, setSession, deleteSession] = useCookie("session_token", {
    initialValue: "",
    path: "/dashboard" // Will only be accessible on /dashboard
  });

  const handleLogin = (token: string) => {
    // Override the default options for this specific update
    setSession(token, {
      secure: true,
      sameSite: "strict",
      maxAgeSeconds: 3600, // 1 hour
      path: "/" // Make available globally
    });
  };

  const handleLogout = () => {
    // deleteCookie accepts a subset of options (path, domain) to ensure correct removal
    deleteSession({ path: "/" });
  };

  return (
    <div>
      {session ? (
        <button onClick={handleLogout}>Logout</button>
      ) : (
        <button onClick={() => handleLogin("abc-123")}>Login Securely</button>
      )}
    </div>
  );
}

API Reference

Parameters

  • key
    • Type: string
    • Description: The name of the cookie to read and write.
  • options (Optional)
    • Type: UseCookieOptions
    • Description: Configuration object for the cookie. Includes initialValue for SSR and default settings for setCookie.
export interface CookieOptions {
  days?: number;           // Defaults to 7 if no expiration is specified
  maxAgeSeconds?: number;
  expires?: Date;
  path?: string;           // Defaults to "/"
  domain?: string;
  secure?: boolean;
  sameSite?: "lax" | "strict" | "none";
}

export interface UseCookieOptions extends CookieOptions {
  /** The initial rendering value used during SSR and the first client render */
  initialValue?: string;
}

Return Array

Returns a tuple containing:

  • value (string | undefined): The current value of the cookie. Strict string. On the very first render, this strictly returns options.initialValue for SSR safety.
  • setCookie ((value: string, setOptions?: CookieOptions) => void): Function to update the cookie. You can override the default hook options by passing setOptions.
  • deleteCookie ((deleteOptions?: Pick<CookieOptions, "path" | "domain">) => void): Function to delete the cookie.

Core Working

  1. Hydration Safe: On the very first render (especially during SSR), the hook strictly returns options.initialValue. This guarantees hydration won't mismatch between the server and the browser.
  2. Reconciliation: Immediately after the component mounts on the client, a useEffect reads the actual cookie from document.cookie and updates the React state to match it.
  3. Strict String Semantics: Unlike local/session storage which parses JSON, useCookie strictly returns literal strings. It will not attempt to automatically run JSON.parse which prevents surprising bugs with numeric or boolean-like strings.
  4. Security Enforced: It actively prevents setting invalid cookie names (by enforcing RFC 6265) and prevents setting sameSite: "none" unless secure: true is also provided.
  5. Byte Size Validation: Protects you from breaking browser limits by calculating the UTF-8 byte weight of your cookie value and aggressively throwing an error if it exceeds the 4096-byte safe limit.

Clone this wiki locally