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