35 lines
840 B
TypeScript
35 lines
840 B
TypeScript
import { useEffect, useState } from 'react';
|
|
|
|
export default function useLocalStorage<T>({
|
|
key,
|
|
initialValue,
|
|
serialize = JSON.stringify,
|
|
deserialize = JSON.parse
|
|
}: {
|
|
key: string;
|
|
initialValue: T;
|
|
serialize?: (value: T) => string;
|
|
deserialize?: (value: string) => T;
|
|
}) {
|
|
const [stored, setStored] = useState(() => {
|
|
try {
|
|
const localStorageValue = window.localStorage.getItem(key);
|
|
if (localStorageValue !== null) {
|
|
return deserialize(localStorageValue);
|
|
} else {
|
|
return initialValue;
|
|
}
|
|
} catch {
|
|
return initialValue;
|
|
}
|
|
});
|
|
useEffect(() => {
|
|
try {
|
|
const serializedState = serialize(stored);
|
|
window.localStorage.setItem(key, serializedState);
|
|
} catch {
|
|
// Ignore
|
|
}
|
|
}, [key, serialize, stored]);
|
|
return [stored, setStored];
|
|
}
|