useCookie
React hook that facilitates the storage, updating and deletion of values within the CookieStore
useCookie manages a single browser cookie by key. It returns a tuple of [cookieValue, updateCookie, refreshCookie]. Call updateCookie with a string to set the cookie or with undefined to delete it. The refreshCookie function re-reads the cookie from the store, which is useful when the cookie may have been modified externally. Options are passed through to js-cookie for controlling path, domain, expiration, and other cookie attributes.
When to Use
- Persisting user preferences (locale, theme, consent flags) in cookies for server-side access
- Reading and writing authentication or session tokens stored in cookies
- Synchronizing cookie state in a component when external code (analytics, third-party scripts) may also modify the cookie
Notes
- SSR considerations: Pass a
defaultValuewhen using SSR so the hook has a value beforedocument.cookieis available on the client. - No cross-component sync: Updating a cookie in one component does not automatically trigger re-renders in other components using the same key. Use a broadcast mechanism if needed.
- See also
useLocalStorageanduseSessionStoragefor Web Storage alternatives that provide cross-tab synchronization via thestorageevent.
Usage
Live Editor
function Demo() { const defaultOption = { path: "/", }; const cookieName = "cookie-key"; const [cookieValue, updateCookie, refreshCookie] = useCookie( cookieName, defaultOption, "default-value" ); const updateButtonClick = () => { updateCookie("new-cookie-value"); }; const deleteButtonClick = () => { updateCookie(undefined); }; const change = () => { if ("cookieStore" in window) { const store = window.cookieStore as any; store.set({ name: cookieName, value: "changed" }); } else { document.cookie = `${cookieName}=changed; path=/`; } }; return ( <div> <p>Click on the button to update or clear the cookie</p> <p color="blue">cookie: {cookieValue || "no value"}</p> <button onClick={updateButtonClick}>Update the cookie</button> <button onClick={deleteButtonClick}>Clear the cookie</button> <button onClick={change}> Changing the cookie through other methods </button> <button onClick={refreshCookie}>Refresh the cookie</button> </div> ); };
Result
API
useCookie
Returns
readonly [UseCookieState, (newValue: UseCookieState | ((prevState: UseCookieState) => UseCookieState)) => void, () => void]: A tuple with the following elements:
- The current value of the cookie.
- A function to update the value of the cookie.
- A function to refresh the value of the cookie, incase other events change it.
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| key | key | string (Required) | - |
| options | option pass to js-cookie | any | - |
| defaultValue | defaultValue, must be required in ssr | string | undefined | - |
useCookieState
Type
export type UseCookieState = string | undefined