useCookie: Persistent State
Best Practices Guide for Browser Cookie Management
Introduction
Managing state that persists beyond a single session and is accessible to the server is essential for authentication and internationalization. The useCookie hook provides a reactive and SSR-safe bridge for browser cookies.
How it works
- Read/Write Symmetry: The hook behaves similarly to
useState, but it also interacts with browser cookies for a specified name. - Isomorphic: It seamlessly handles reading cookies from request headers during SSR and from
document.cookieon the client. - Synchronization: Components re-render automatically when the cookie is updated by any other component using the same name.
- Automatic Verification: By default, it re-verifies the cookie value on window focus to handle external changes.
Why use useCookie?
- Server-Side Availability: Unlike
localStorage, cookies are sent to the server, enabling personalized SSR. - Security Control: Supports standard cookie security options like
secure,sameSite, andhttpOnly(for server-managed scenarios). - Stable Interface: Provides a familiar
[value, set, clear]tuple.
See Also
For a detailed technical breakdown and additional implementation patterns, refer to the following resources:
Key Takeaways
- Keep it small: Cookies are generally limited to ~4KB. Avoid storing large objects; use them for identifiers or simple preference flags.
- Set Expiration: Use the
expiresormaxAgeoptions in thesetfunction to control how long the data persists. - Security First: For sensitive data, always use
secure: true(requires HTTPS) and appropriatesameSitepolicies. - SSR Awareness: Use
useCookiefor state that directly impacts the initial page render (e.g., currency, language, theme) to avoid client-side UI shifts. - Update on Focus:
updateOnRefocusdefaults totrue, so external changes (by other scripts or third-party widgets) are picked up when the window regains focus. Only passupdateOnRefocus: falseif that re-verification is undesirable.