Skip to Content
ohooks

useCookie

Reads, writes, and deletes a browser cookie reactively using useSyncExternalStore.

Loading preview...

The useCookie hook reads, updates, and removes a browser cookie reactively across all components and tabs using useSyncExternalStore and the Cookie Store API when available.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useCookie.json

Usage

Examples

Persisting a Theme Preference

Provide a defaultValue so the hook returns a fallback when the cookie has not been set yet or during server rendering.

Overriding Attributes Per Write

Pass cookie attributes as the second argument to setCookie to override the default attributes for a specific update.

API Reference

CookieAttributes

Attributes used when writing or deleting the cookie (path, domain, maxAge, expires, secure, and sameSite).

Property
Specification
path?
stringdefault:'/'
Cookie path scope
domain?
string
Domain that the cookie is available to
expires?
union
Expiration date or number of days until expiration
maxAge?
number
Maximum age of the cookie in seconds
secure?
union
Whether the cookie should only be transmitted over HTTPS
sameSite?
union
Cross-site request forgery protection mode

UseCookieOptions

Configuration options for the cookie hook, extending CookieAttributes with a fallback defaultValue.

Property
Specification
defaultValue?
uniondefault:null
Fallback value returned when the cookie does not exist
path?
stringdefault:'/'
Cookie path scope
domain?
string
Domain that the cookie is available to
expires?
union
Expiration date or number of days until expiration
maxAge?
number
Maximum age of the cookie in seconds
secure?
union
Whether the cookie should only be transmitted over HTTPS
sameSite?
union
Cross-site request forgery protection mode