HooksuseCookie

useCookie()

The useCookie() hook provides a wrapper around the native document.cookie API, making it easier to read, update, and remove cookies within your React components.

Import

typescript
import { useCookie } from 'the-react-hooks';

Usage

Current Cookie Value (key: user_preference)
No cookie found (null)
Component.tsx
import { useCookie } from 'the-react-hooks';

export const Component = () => {
  const [value, updateCookie, deleteCookie] = useCookie('my_cookie_key');

  const handleSet = () => {
    updateCookie('Hello World', { days: 7 });
  };

  return (
    <div>
      <p>Current Value: {value}</p>
      
      <button onClick={handleSet}>
        Set Cookie
      </button>
      
      <button onClick={deleteCookie}>
        Delete Cookie
      </button>
    </div>
  );
}

API

Arguments

  • key string The name of the cookie key you want to manage.

Returns

Returns an array (tuple) containing:
  • [0] value string | null The current value of the cookie.
  • [1] updateCookie (value: string, options?: CookieOptions) => void Function to update the cookie. Accepts the new value and an optional configuration object.
  • [2] deleteCookie () => void Function to delete the cookie (expires it immediately).

Types

CookieOptions interface:
  • days?: number (Default: 7)
  • path?: string (Default: ‘/‘)
  • domain?: string
  • secure?: boolean
  • sameSite?: ‘Lax‘ | ‘Strict‘ | ‘None‘ (Default: ‘Lax‘)