File size: 1,451 Bytes
be02369 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import { useState, useEffect } from 'react';
// A hook for persisting state to localStorage, now user-agnostic.
export function useLocalStorage<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>] {
// Create a static key.
const storageKey = `yuki-app-${key}`;
const [storedValue, setStoredValue] = useState<T>(() => {
try {
if (typeof window === 'undefined') return initialValue;
const item = window.localStorage.getItem(storageKey);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
useEffect(() => {
try {
const item = window.localStorage.getItem(storageKey);
if (item) {
setStoredValue(JSON.parse(item));
}
} catch (error) {
console.error(error);
}
}, [storageKey]);
const setValue: React.Dispatch<React.SetStateAction<T>> = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
if (typeof window !== 'undefined') {
window.localStorage.setItem(storageKey, JSON.stringify(valueToStore));
}
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
} |