Yuki / hooks /useLocalStorage.ts
Severian's picture
Upload 43 files
be02369 verified
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];
}