useCookie
A hook that allows to manage cookies.
This hook requires the following packages:
js-cookie
npm install js-cookie
yarn add js-cookie
pnpm add js-cookie
Example
import useCookie from "@/hooks/useCookie";
export default function UseCookieExample() {
const [cookie, setCookie, removeCookie] = useCookie("example-cookie");
return (
<div className="flex flex-col items-center justify-center gap-4 p-4 text-ctp-text">
<p>Cookie: {cookie}</p>
<button
className="rounded bg-ctp-blue px-4 py-2 text-ctp-base"
onClick={() => setCookie("example-value")}
>
Set cookie
</button>
<button
className="rounded bg-ctp-red px-4 py-2 text-ctp-base"
onClick={() => removeCookie()}
>
Delete cookie
</button>
</div>
);
}
Code
import { useCallback, useState } from "react";
import Cookies from "js-cookie";
type CookiesReturn = [
string | null,
(newValue: string, options?: Cookies.CookieAttributes) => void,
() => void,
];
/**
* A hook that allows to manage cookies.
* @param {string} cookieName - The name of the cookie.
* @requires js-cookie
* @returns {CookiesReturn} An array of three elements:
* 1. The current value of the cookie.
* 2. A function to update the cookie value.
* 3. A function to delete the cookie.
*/
export default function useCookie(cookieName: string): CookiesReturn {
const [value, setValue] = useState<string | null>(
() => Cookies.get(cookieName) || null,
);
const updateCookie = useCallback(
(newValue: string, options?: Cookies.CookieAttributes) => {
Cookies.set(cookieName, newValue, options);
setValue(newValue);
},
[cookieName],
);
const deleteCookie = useCallback(() => {
Cookies.remove(cookieName);
setValue(null);
}, [cookieName]);
return [value, updateCookie, deleteCookie];
}