Skip to main content

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

  1. Read/Write Symmetry: The hook behaves similarly to useState, but it also interacts with browser cookies for a specified name.
  2. Isomorphic: It seamlessly handles reading cookies from request headers during SSR and from document.cookie on the client.
  3. Synchronization: Components re-render automatically when the cookie is updated by any other component using the same name.
  4. 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, and httpOnly (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 expires or maxAge options in the set function to control how long the data persists.
  • Security First: For sensitive data, always use secure: true (requires HTTPS) and appropriate sameSite policies.
  • SSR Awareness: Use useCookie for state that directly impacts the initial page render (e.g., currency, language, theme) to avoid client-side UI shifts.
  • Update on Focus: updateOnRefocus defaults to true, so external changes (by other scripts or third-party widgets) are picked up when the window regains focus. Only pass updateOnRefocus: false if that re-verification is undesirable.