25 lines
823 B
TypeScript
25 lines
823 B
TypeScript
import { type Dispatch, type SetStateAction, useEffect, useState } from "react";
|
|
|
|
export function usePersistentState<T>(key: string, initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
|
|
const [value, setValue] = useState<T>(() => {
|
|
const fallback = typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
|
|
if (typeof window === "undefined") return fallback;
|
|
try {
|
|
const stored = window.localStorage.getItem(key);
|
|
return stored ? JSON.parse(stored) as T : fallback;
|
|
} catch {
|
|
return fallback;
|
|
}
|
|
});
|
|
|
|
useEffect(() => {
|
|
try {
|
|
window.localStorage.setItem(key, JSON.stringify(value));
|
|
} catch {
|
|
// Storage can be unavailable in private mode; in-memory state still works.
|
|
}
|
|
}, [key, value]);
|
|
|
|
return [value, setValue];
|
|
}
|