kawkab-frontend
Version:
Kawkab frontend is a frontend library for the Kawkab framework
26 lines (25 loc) • 906 B
JavaScript
import { useState, useCallback } from 'react';
import { Cookie } from '../utils/cookie.js';
/**
* A React hook to manage a single cookie value.
* The component will re-render when the cookie value changes.
*
* @param key The name of the cookie.
* @param defaultValue The default value if the cookie is not set.
* @returns A state-like array: [value, updateValue, removeValue].
*/
export function useCookie(key, defaultValue) {
const [value, setValue] = useState(() => {
const cookieValue = Cookie.get(key);
return cookieValue !== null ? cookieValue : defaultValue;
});
const updateValue = useCallback((newValue, days) => {
Cookie.set(key, newValue, days);
setValue(newValue);
}, [key]);
const removeValue = useCallback(() => {
Cookie.remove(key);
setValue(undefined);
}, [key]);
return [value, updateValue, removeValue];
}