logseq-calendar/lib/persistentState.ts
2023-08-24 13:37:23 -04:00

15 lines
457 B
TypeScript

import { useEffect, useState } from "react";
export function usePersistentState<T>(key: string, defaultValue: T) {
const [value, setValue] = useState(() => {
const value = window.localStorage.getItem(key);
if (value === "undefined") return defaultValue;
return value ? JSON.parse(value) : defaultValue;
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}