shadcn-ahooks

useCookieState

A Hook that store state into Cookie.

Overview

A Hook that store state into Cookie.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCookieState.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCookieState.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCookieState.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCookieState.json

A Hook that store state into Cookie.

Examples

SetState can receive function

API

type State = string | undefined;

type SetState = (
  newValue?: State | ((prevState?: State) => State),
  options?: Cookies.CookieAttributes,
) => void;

const [state, setState]: [State, SetState] = useCookieState(
  cookieKey: string,
  options?: Options,
);

If you want to delete this record from document.cookie, use setState() or setState(undefined).

Params

| Property | Description | Type | Default | | | - | | cookieKey | The key of Cookie | string | - | | options | Optional. Cookie configuration | Options | - |

Result

| Property | Description | Type | | -- | - | - | ----- | | defaultValue | Optional. Default value, but not store to Cookie | string | undefined | (() => (string \| undefined)) | undefined | | expires | Optional. Set Cookie expiration time | number | Date | - | | path | Optional. Specify available paths | string | / | | domain | Optional. Specify available domain. Default creation domain | string | - | | secure | Optional. Specify whether the Cookie can only be transmitted over secure protocol as https | boolean | false | | sameSite | Optional. Specify whether the browser can send this Cookie along with cross-site requests | strict | lax | none | - |

Options is same as js-cookie attributes.

On this page