Skip to content

Instantly share code, notes, and snippets.

@enjoylife
Created March 8, 2019 05:13
Show Gist options
  • Save enjoylife/cfdd2cceeda0ff5098cea57d81a8d9d0 to your computer and use it in GitHub Desktop.
Save enjoylife/cfdd2cceeda0ff5098cea57d81a8d9d0 to your computer and use it in GitHub Desktop.
// @flow
import {useState, useEffect} from 'react';
// Hook
export default function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
// Get from local storage by key
if (__BROWSER__) {
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} else {
return initialValue;
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
return initialValue;
}
});
useEffect(() => {
// eslint-disable-next-line no-console
__DEV__ && console.log(`[localstorage] - ${key}`, storedValue);
try {
if (__BROWSER__) {
window.localStorage.setItem(key, JSON.stringify(storedValue));
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment