This article demonstrates building a custom React hook, useCookie
, for streamlined browser cookie management. Browser cookies offer a simple method for storing persistent data across sessions or application sections.
1. Cookie Utility Functions
Before creating the hook, we'll define helper functions for common cookie operations: setting, retrieving, and removing cookies.
setCookie
: Setting or Updating a CookieThis function saves a key-value pair, optionally specifying an expiration time.
<code class="language-typescript">export function setCookie(key: string, value: unknown, expireDays = 1): void { const d = new Date(); d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000); document.cookie = `${key}=${value}; expires=${d.toUTCString()}; path=/`; }</code>
setCookie("theme", "dark", 7);
// Sets a cookie lasting 7 daysgetCookie
: Retrieving a Cookie ValueThis function retrieves a cookie's value using its key.
<code class="language-typescript">export function getCookie(key: string): string | undefined { const name = `${key}=`; const decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(";"); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) === " ") { c = c.substring(1); } if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } return undefined; }</code>
document.cookie
, splits it into an array, and searches for the specified key. Returns the value or undefined
.const theme = getCookie("theme");
// Retrieves the "theme" valueremoveCookie
: Deleting a CookieThis function removes a cookie by overwriting it with an empty value and no expiration.
<code class="language-typescript">export function removeCookie(key: string): void { document.cookie = `${key}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`; }</code>
removeCookie("theme");
// Deletes the "theme" cookie2. The useCookie
Hook
The useCookie
hook integrates the utility functions with React's useState
for elegant cookie management within components.
<code class="language-typescript">import { useState } from "react"; import { getCookie, setCookie, removeCookie } from "@/utils/cookie"; export default function useCookie<T>(key: string, initialValue: T): [T | undefined, (action: T | ((prevState: T) => T)) => void, () => void] { const [value, setValue] = useState(() => getCookie(key) as T || initialValue); // ...rest of the hook implementation }</code>
key
(cookie key), initialValue
(default value if cookie doesn't exist).initialValue
.The handleDispatch
function updates both the state and the cookie.
<code class="language-typescript"> const handleDispatch = (action: T | ((prevState: T) => T)) => { if (typeof action === "function") { setValue((prevState) => { const newValue = (action as (prevState: T) => T)(prevState); setCookie(key, newValue); return newValue; }); } else { setValue(action); setCookie(key, action); } };</code>
The clearState
function removes the cookie and resets the state.
<code class="language-typescript">export function setCookie(key: string, value: unknown, expireDays = 1): void { const d = new Date(); d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000); document.cookie = `${key}=${value}; expires=${d.toUTCString()}; path=/`; }</code>
undefined
.The hook returns an array: current value, dispatcher function, and clear function.
<code class="language-typescript">export function getCookie(key: string): string | undefined { const name = `${key}=`; const decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(";"); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) === " ") { c = c.substring(1); } if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } return undefined; }</code>
3. Using the useCookie
Hook
Example usage in a React component:
<code class="language-typescript">export function removeCookie(key: string): void { document.cookie = `${key}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`; }</code>
theme
is stored in a cookie, persists across sessions, and updates synchronously. clearTheme
removes the cookie and resets the state.4. Advantages of the useCookie
Hook
Conclusion
The useCookie
hook simplifies cookie management in React, promoting type safety and clean code. It streamlines cookie-based state management, eliminating repetitive code.
The above is the detailed content of Managing Browser Cookies in React with useCookie Hook. For more information, please follow other related articles on the PHP Chinese website!