auditforge / frontend /src /hooks /useLocalStorage.tsx
Kaballas's picture
initialize project structure with essential configurations and components
56b6519
raw
history blame
744 Bytes
import { useState } from 'react';
export const useLocalStorage = (
keyName: string,
defaultValue: string | null,
) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const value = window.localStorage.getItem(keyName);
if (value) {
return JSON.parse(value);
} else {
window.localStorage.setItem(keyName, JSON.stringify(defaultValue));
return defaultValue;
}
} catch (err) {
return defaultValue;
}
});
const setValue = (newValue: string | null) => {
try {
window.localStorage.setItem(keyName, JSON.stringify(newValue));
} catch (err) {
console.error(err);
}
setStoredValue(newValue);
};
return [storedValue, setValue];
};