useCookie
This hook use js-cookie as the parser. You can use this hook to get, set and/or remove cookies.
API
function useCookie(
name: string,
options?: {
defaultValue?: string;
polling?: boolean;
pollingInterval?: number;
validate?: (value: string) => boolean;
}
): [
value: string | undefined,
setCookie: (
newValue:
| string
| undefined
| ((prevValue: string | undefined) => string | undefined),
attributes?: CookieAttributes
) => void
];
interface CookieAttributes {
path?: string;
domain?: string;
secure?: boolean;
expires?: number | Date;
sameSite?: "strict" | "Strict" | "lax" | "Lax" | "none" | "None";
}
Params:
name: Cookie name.options: Options object.options.defaultValue: Default value. It will be returnd when the specified cookie is non-existant.options.polling: Pollingly update cookie value. Default isfalse.options.pollingInterval: Polling interval time, in milliseconds. Default is100.options.validate: Validate the value got from cookie. If this function returnfalse, thedefaultValuewill be used.
Results:
value: Cookie value.setCookie: A function that can set or remove the named cookie. It accepts two params:newValue: The new cookie value. If it isundefinedor a function that returnsundefined, the named cookie will be cleared, and theoptions.defaultValuewill be returnd asvalue.attributes: Cookie attributes. See js-cookie attributes.
Example
Cookie value: default value
import React from "react";
import { useCookie } from "@lilib/hooks";
function Example() {
const [value, setCookie] = useCookie("name", {
polling: true,
defaultValue: "default value",
});
return (
<>
<div>
<button onClick={() => setCookie(Math.random().toString())}>
Set random cookie
</button>{" "}
<button onClick={() => setCookie(undefined)}>Remove</button>
</div>
<div>Cookie value: {value}</div>
</>
);
}
export default Example;