mirror of
https://github.com/piyush-eon/tanstack-query-weather-app.git
synced 2025-11-24 05:11:19 +00:00
24 lines
612 B
TypeScript
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;
|
|
}
|