logseq-calendar/lib/persistentState.ts

16 lines
457 B
TypeScript
Raw Permalink Normal View History

2023-08-24 17:37:23 +00:00
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];
}