useCookieState

State Management

A React hook for managing state that persists in browser cookies with SSR support, automatic encoding/decoding, and configurable expiration options.

Installation

npm install @thibault.sh/hooks

API Reference

Signature


interface CookieOptions {
  days?: number;
  path?: string;
  domain?: string;
  secure?: boolean;
  sameSite?: "Strict" | "Lax" | "None";
}

function useCookieState(
  name: string,
  initialValue: string
): [
  string | null,
  (newValue: string, options?: CookieOptions) => void,
  () => void
]

Parameters

NameTypeDescriptionDefault
name
string
The name of the cookie to manage.-
initialValue
string
The default value to use when no cookie exists or on server-side.-

Returns

[string | null, setCookie, deleteCookie]

A tuple containing the current value, setter function, and delete function.

Properties:

PropertyTypeDescription
value
string | null
Current cookie value as string, or null if not set.
setCookie
(newValue: string, options?: CookieOptions) => void
Function to update the cookie with optional configuration.
deleteCookie
() => void
Function to remove the cookie from the browser.