Skip to main content

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 is false.
    • options.pollingInterval: Polling interval time, in milliseconds. Default is 100.
    • options.validate: Validate the value got from cookie. If this function return false, the defaultValue will 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 is undefined or a function that returns undefined, the named cookie will be cleared, and the options.defaultValue will be returnd as value.
    • 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;