useCookie
有助於在 CookieStore 中存儲、更新和刪除值的 hook
useCookie 提供響應式的瀏覽器 cookie 讀寫。它回傳一個元組,包含當前 cookie 值(或 null)和一個更新 cookie 的函式。支援設定 cookie 的各種屬性(過期時間、路徑、域名、安全性等)。刪除 cookie 可透過將值設為 null 或 undefined。
使用場景
- 讀取和寫入使用者偏好設定到 cookie
- 管理認證 token 或工作階段資訊
- 建構需要 cookie 存取的同意管理或功能旗標系統
注意事項
- SSR 安全:在伺服器端渲染時回傳
null。伺服器上不會存取document.cookie。 - Cookie 屬性:支援所有標準 cookie 屬性,包括
expires、path、domain、secure、sameSite和httpOnly。 - 相關 hooks:另請參閱
useLocalStorage和useSessionStorage用於 Web Storage API 的替代持久化方案。
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>點擊按鈕以更新或清除 cookie</p> <p color="blue">cookie:{cookieValue || "無值"}</p> <button onClick={updateButtonClick}>更新 cookie</button> <button onClick={deleteButtonClick}>清除 cookie</button> <button onClick={change}> 通過其他方法更改 cookie </button> <button onClick={refreshCookie}>刷新 cookie</button> </div> ); }
Result
API
useCookie
Returns
readonly [UseCookieState, (newValue: UseCookieState | ((prevState: UseCookieState) => UseCookieState)) => void, () => void]: 包含以下元素的元組:
- cookie 的當前值。
- 更新 cookie 值的函數。
- 刷新 cookie 值的函數,以防其他事件更改它。
Arguments
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| key | 键值 | string (必填) | - |
| options | 透传给 js-cookie 的参数 | any | - |
| defaultValue | 默认值,ssr必须传递 | string | undefined | - |
useCookieState
Type
export type UseCookieState = string | undefined