24 lines
577 B
TypeScript
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;
|
|
}
|