15 lines
457 B
TypeScript
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];
|
|
}
|