Skip to content
On this page

useCookieState

A Hook that store state into Cookie.

Code demonstration

Basic usage

Advanced Usage-Receivable functions

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,
);
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,
);

Note

If you want to remove this data from the document.cookie, use the setState() or setState (undefined).

Params

PropertyDescriptionTypeDefault
cookieKeyThe key of Cookiestring-
optionsOptional. Cookie configurationOptions-

Result

PropertyDescriptionType
stateLocal Cookie valueReadonly<Ref<string>> | 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

Source

SourceDocsDemo