25 lines
551 B
TypeScript
25 lines
551 B
TypeScript
import { useEffect, useState } from 'react';
|
|
|
|
export function useLocalStorageState<T>(key: string, initialValue: T) {
|
|
const [value, setValue] = useState<T>(() => {
|
|
try {
|
|
const raw = window.localStorage.getItem(key);
|
|
if (raw == null) return initialValue;
|
|
return JSON.parse(raw) as T;
|
|
} catch {
|
|
return initialValue;
|
|
}
|
|
});
|
|
|
|
useEffect(() => {
|
|
try {
|
|
window.localStorage.setItem(key, JSON.stringify(value));
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}, [key, value]);
|
|
|
|
return [value, setValue] as const;
|
|
}
|
|
|