Skip to content

Instantly share code, notes, and snippets.

@scorsi
Created February 27, 2020 15:07
Show Gist options
  • Save scorsi/587dd77b598c001e2657df9530660896 to your computer and use it in GitHub Desktop.
Save scorsi/587dd77b598c001e2657df9530660896 to your computer and use it in GitHub Desktop.
A hook useful to get/set data from/to localstorage
import { useState } from 'react';
export default (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