kawkab-frontend
Version:
Kawkab frontend is a frontend library for the Kawkab framework
43 lines (42 loc) • 1.57 kB
JavaScript
import { useState, useCallback, useEffect } from 'react';
import { LocalStorage } from '../utils/localStorage.js';
/**
* A React hook to manage a value in localStorage.
* The component will re-render when the value changes.
* Automatically handles JSON serialization and parsing.
*
* @param key The key for the localStorage item.
* @param defaultValue The default value if nothing is stored.
* @returns A state-like array: [value, setValue, removeValue].
*/
export function useLocalStorage(key, defaultValue) {
const [value, setValue] = useState(() => {
return LocalStorage.get(key) ?? defaultValue;
});
const updateValue = useCallback((newValue) => {
LocalStorage.set(key, newValue);
setValue(newValue);
}, [key]);
const removeValue = useCallback(() => {
LocalStorage.remove(key);
setValue(undefined);
}, [key]);
// Optional: Listen for changes from other tabs/windows
useEffect(() => {
const handleStorageChange = (event) => {
if (event.key === key && event.storageArea === window.localStorage) {
try {
setValue(event.newValue ? JSON.parse(event.newValue) : undefined);
}
catch {
setValue(event.newValue);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, [key]);
return [value, updateValue, removeValue];
}