useCookie

A Hook that store state into Cookie.

Examples

Store state into Cookie

Refresh this page and you will get the state from Cookie.

SetState can receive function

0

SetState can receive function

Function updater is also acceptable with useCookieState's setState,similar to how useState is used.

0

Use the option property to configure Cookie

'Available options: defaultValue、expires、path、domain、secure、sameSite etc.'

API

type State = string | undefined;type SetState = (  newValue?: State | ((prevState?: State) => State),  options?: Cookies.CookieAttributes,) => void;const [state, setState]: [Accessor<State>, SetState] = useCookie(  cookieKey: string,  options?: Options,);
type State = string | undefined;type SetState = (  newValue?: State | ((prevState?: State) => State),  options?: Cookies.CookieAttributes,) => void;const [state, setState]: [Accessor<State>, SetState] = useCookie(  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 valueAccessor<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.