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

PropertyDescriptionTypeDefault
cookieKeyThe key of Cookiestring-
optionsOptional. Cookie configurationOptions-

Result

PropertyDescriptionType
stateLocal Cookie valuestring | undefined
setStateUpdate Cookie valueSetState

setState can update cookie options, which will be merged with the options set by useCookieState.

const targetOptions = { ...options, ...updateOptions }

Options

PropertyDescriptionTypeDefault
defaultValueOptional. Default value, but not store to Cookiestring | undefined | (() => (string | undefined))undefined
expiresOptional. Set Cookie expiration timenumber | Date-
pathOptional. Specify available pathsstring/
domainOptional. Specify available domain. Default creation domainstring-
secureOptional. Specify whether the Cookie can only be transmitted over secure protocol as httpsbooleanfalse
sameSiteOptional. Specify whether the browser can send this Cookie along with cross-site requestsstrict | lax | none-

Options is same as js-cookie attributes.

On this page