Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save blopa/61503207033f5fd32da3068fbf85e38e to your computer and use it in GitHub Desktop.
Save blopa/61503207033f5fd32da3068fbf85e38e to your computer and use it in GitHub Desktop.
Code for post "My blog now has Stories, and I'm not sure why"
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment