Skip to content

useCookieState

Persists a string state value in a browser cookie.

Persists a string state value in a browser cookie.

Import

import { useCookieState } from '@kamod-ch/hooks'

Live demo

Basic demo

Persists a string state value in a browser cookie.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useCookieState } from '@kamod-ch/hooks'

const key = 'kamod-hooks-demo-use-cookie-state'

export default function UseCookieStateDemo() {
  const [value, setValue] = useCookieState(key, { defaultValue: 'cookie', path: '/' })

  return (
    <div>
      <input value={value ?? ''} onInput={(event) => setValue(event.currentTarget.value, { path: '/' })} />
      <p><strong>Cookie value:</strong> {value ?? 'undefined'}</p>
      <button type="button" onClick={() => setValue(undefined, { path: '/', expires: -1 })}>Delete cookie</button>
    </div>
  )
}

API

TypeScript signature
export type State = string | undefined;
export interface CookieAttributes {
    /**
     * Define when the cookie will be removed. Value can be a Number
     * which will be interpreted as days from time of creation or a
     * Date instance. If omitted, the cookie becomes a session cookie.
     */
    expires?: number | Date | undefined;
    /**
     * Define the path where the cookie is available. Defaults to '/'
     */
    path?: string | undefined;
    /**
     * Define the domain where the cookie is available. Defaults to
     * the domain of the page where the cookie was created.
     */
    domain?: string | undefined;
    /**
     * A Boolean indicating if the cookie transmission requires a
     * secure protocol (https). Defaults to false.
     */
    secure?: boolean | undefined;
    /**
     * Asserts that a cookie must not be sent with cross-origin requests,
     * providing some protection against cross-site request forgery
     * attacks (CSRF)
     */
    sameSite?: 'strict' | 'Strict' | 'lax' | 'Lax' | 'none' | 'None' | undefined;
    /**
     * An attribute which will be serialized, conformably to RFC 6265
     * section 5.2.
     */
    [property: string]: any;
}
export interface Options extends CookieAttributes {
    defaultValue?: State | (() => State);
}
declare const useCookieState: (cookieKey: string, options?: Options) => readonly [string, (this: unknown, newValue: string | ((prevState: State) => State), newOptions?: CookieAttributes) => void];
export default useCookieState;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.

Related hooks