mirror of
https://github.com/LCE-Hub/LCE-Emerald-Launcher.git
synced 2026-07-19 00:37:07 +00:00
23 lines
797 B
TypeScript
23 lines
797 B
TypeScript
import { useState, useCallback } from 'react';
|
|
export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] {
|
|
const [storedValue, setStoredValue] = useState<T>(() => {
|
|
try {
|
|
const item = window.localStorage.getItem(key);
|
|
return item ? JSON.parse(item) : initialValue;
|
|
} catch (error) {
|
|
return initialValue;
|
|
}
|
|
});
|
|
|
|
const setValue = useCallback((value: T | ((val: T) => T)) => {
|
|
try {
|
|
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
setStoredValue(valueToStore);
|
|
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
}, [key, storedValue]);
|
|
|
|
return [storedValue, setValue];
|
|
} |