UNPKG

kawkab-frontend

Version:

Kawkab frontend is a frontend library for the Kawkab framework

26 lines (25 loc) 903 B
import { useState, useCallback } from 'react'; import { Cookie } from '../utils/cookie'; /** * 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]; }