useCookieState

State Management

A React hook that manages state in browser cookies, with support for cookie options and expiration.

Demo

This theme preference persists in a cookie and survives browser restarts:

Installation

npm install @thibault.sh/hooks

Usage

import { useCookieState } from '@thibault.sh/hooks/useCookieState';

function ConsentBanner() {
  const [consent, setConsent, deleteConsent] = useCookieState('cookie-consent', 'pending');
  
  const acceptAll = () => {
    setConsent('accepted', {
      maxAge: 365 * 24 * 60 * 60, // 1 year in seconds
      path: '/',
      secure: true,
      sameSite: 'strict'
    });
  };

  if (consent === 'accepted') {
    return null;
  }

  return (
    <div className="banner">
      <p>We use cookies to improve your experience</p>
      <button onClick={acceptAll}>Accept All</button>
      <button onClick={() => setConsent('minimal')}>Accept Necessary Only</button>
    </div>
  );
}

API

Parameters

  • name
    string

    The name of the cookie

  • initialValue
    string

    The initial value to use if no cookie exists

Returns

{[string | null, (newValue: string, options?: CookieOptions) => void, () => void]} A tuple containing:

Cookie Options

interface CookieOptions {
  path?: string;        // Cookie path (default: current path)
  // Additional options may be available - check the implementation
}

Note: Additional cookie options may be available. Please refer to the implementation or types for the complete list of supported options.

Features

  • Cookie Management

    Full control over cookie attributes and expiration

  • Browser Persistence

    State persists across browser sessions and restarts

  • Security Options

    Support for secure, httpOnly, and sameSite attributes

  • Delete Support

    Built-in function to remove cookies when needed

Language Preference Example

import { useCookieState } from '@thibault.sh/hooks';

function LanguageSelector() {
  const [language, setLanguage, resetLanguage] = useCookieState(
    'preferred-language',
    'en'
  );

  const updateLanguage = (newLang: string) => {
    setLanguage(newLang, {
      path: '/'
    });
    window.location.reload();
  };

  return (
    <div>
      <select 
        value={language || 'en'} 
        onChange={(e) => updateLanguage(e.target.value)}
      >
        <option value="en">English</option>
        <option value="es">Español</option>
        <option value="fr">Français</option>
      </select>
      <button onClick={resetLanguage}>
        Reset to Browser Default
      </button>
    </div>
  );
}

Authentication Token Example

import { useCookieState } from '@thibault.sh/hooks';

function AuthManager() {
  const [token, setToken, removeToken] = useCookieState('auth-token', '');

  const login = async (credentials: { username: string; password: string }) => {
    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify(credentials)
      });
      const { token } = await response.json();
      
      setToken(token, {
        path: '/'
      });
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  const logout = () => {
    removeToken();
    window.location.href = '/login';
  };

  return (
    <div>
      {token ? (
        <button onClick={logout}>Logout</button>
      ) : (
        <button onClick={() => login({ username: 'test', password: 'test' })}>
          Login
        </button>
      )}
    </div>
  );
}