Files
whatsapp-bridge/ui/src/hooks/useLocalStorage.ts
T
2026-09-17 06:11:14 +08:00

24 lines
577 B
TypeScript

import { useEffect, useState } from "react";
export function useLocalStorage<T = unknown>(key: string, initialValue: T) {
const [state, setState] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(state));
} catch (error) {
console.log(error);
}
}, [state]);
return [state, setState] as const;
}