useCookie
This hook uses js-cookie as the parser. You can use this hook to get, set and/or remove cookies.
API
interface UseCookieOptions {
defaultValue?: string;
polling?: boolean;
pollingInterval?: number;
validate?: (value: string) => boolean;
}
function useCookie(
name: string,
options: UseCookieOptions & { defaultValue: string },
): [
value: string,
setCookie: (
newValue: string | undefined | ((prevValue: string) => string | undefined),
attributes?: CookieAttributes,
) => void,
];
function useCookie(
name: string,
options?: UseCookieOptions,
): [
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";
}
Parameters:
name: Cookie name.options: Options object.options.defaultValue: Default value. It will be returned when the specified cookie doesn't exist. When set, the returnedvaluetype no longer includesundefined.options.polling: Whether to poll for cookie changes. Default isfalse.options.pollingInterval: Polling interval time, in milliseconds. Default is100.options.validate: Validate the value got from the cookie. If this function returnsfalse, 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 returned asvalue.attributes: Cookie attributes. See js-cookie attributes.
Notes
- Important: Removing a cookie requires the same
attributesas when it was set (especiallypathanddomain); otherwise the removal silently fails. - Cookie changes made elsewhere (server responses, other scripts) are not pushed to the hook; enable
polling: trueto detect them. - Values are strings — no serialization is applied. Use
JSON.stringifytogether withvalidatefor structured data. - Returns
defaultValuein non-browser environments. Thevaluestarts withdefaultValueon the first render and is synchronized with the cookie right after mounting (before the browser paints), so server-rendered and client-hydrated output stay consistent.
Example
The following example sets and removes a cookie; open this page in another tab to see polling keep the values in sync.
Cookie value: default value
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;