tanstack-query-weather-app2/src/hooks/use-local-storage.ts
Piyush Agarwal d1ad533352 Klimate App
2024-11-07 11:47:30 +05:30

24 lines
612 B
TypeScript

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