Home >Web Front-end >JS Tutorial >Managing Browser Cookies in React with useCookie Hook

Managing Browser Cookies in React with useCookie Hook

Barbara Streisand
Barbara StreisandOriginal
2025-01-27 16:40:09380browse

Managing Browser Cookies in React with useCookie Hook

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 Cookie

This 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>
  • Functionality: Accepts a key, value, and optional expiration (defaulting to 1 day). It calculates the expiration date and sets the cookie accordingly.
  • Example: setCookie("theme", "dark", 7); // Sets a cookie lasting 7 days

getCookie: Retrieving a Cookie Value

This 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>
  • Mechanism: Decodes document.cookie, splits it into an array, and searches for the specified key. Returns the value or undefined.
  • Example: const theme = getCookie("theme"); // Retrieves the "theme" value

removeCookie: Deleting a Cookie

This 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>
  • Example: removeCookie("theme"); // Deletes the "theme" cookie

2. The useCookie Hook

The useCookie hook integrates the utility functions with React's useState for elegant cookie management within components.


Hook Initialization

<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>
  • Parameters: key (cookie key), initialValue (default value if cookie doesn't exist).
  • State Initialization: Retrieves the cookie value or uses initialValue.

Dispatching State Changes

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>
  • Mechanism: Handles both direct value updates and functional updates (for state transformations). It ensures cookie synchronization.

Clearing the State

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>
  • Functionality: Removes the cookie and sets the state to undefined.

Returning the Hook's API

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>
  • Key Aspects: The 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

  • Simplified Cookie Management: Encapsulates cookie logic.
  • State Synchronization: Keeps React state and cookies in sync.
  • Error Handling: Includes mechanisms for decoding and handling cookies.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn