-
Notifications
You must be signed in to change notification settings - Fork 0
useCookie
Saurav-TB-Pandey edited this page Aug 10, 2026
·
1 revision
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.
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>
);
}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>
);
}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>
);
}-
key- Type:
string - Description: The name of the cookie to read and write.
- Type:
-
options(Optional)- Type:
UseCookieOptions - Description: Configuration object for the cookie. Includes
initialValuefor SSR and default settings forsetCookie.
- Type:
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;
}Returns a tuple containing:
-
value(string | undefined): The current value of the cookie. Strict string. On the very first render, this strictly returnsoptions.initialValuefor SSR safety. -
setCookie((value: string, setOptions?: CookieOptions) => void): Function to update the cookie. You can override the default hook options by passingsetOptions. -
deleteCookie((deleteOptions?: Pick<CookieOptions, "path" | "domain">) => void): Function to delete the cookie.
-
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. -
Reconciliation: Immediately after the component mounts on the client, a
useEffectreads the actual cookie fromdocument.cookieand updates the React state to match it. -
Strict String Semantics: Unlike local/session storage which parses JSON,
useCookiestrictly returns literal strings. It will not attempt to automatically runJSON.parsewhich prevents surprising bugs with numeric or boolean-like strings. -
Security Enforced: It actively prevents setting invalid cookie names (by enforcing RFC 6265) and prevents setting
sameSite: "none"unlesssecure: trueis also provided. - 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.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM