Created
December 4, 2020 13:01
-
-
Save xergiodf/43b2db7b59b4f6174e6cb0fbc5a9e007 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const useStorage = (key, initialValue, storage) => { | |
| // Pass initial state function to useState so logic is only executed once | |
| const [storedValue, setStoredValue] = useState(() => { | |
| try { | |
| const item = storage.getItem(key) | |
| return item ? JSON.parse(item) : initialValue | |
| } catch (error) { | |
| console.error(error) | |
| return initialValue | |
| } | |
| }) | |
| useEffect(() => { | |
| try { | |
| // Update storage every time the value is changed | |
| storage.setItem(key, JSON.stringify(storedValue)) | |
| } catch (e) { | |
| console.error(e) | |
| } | |
| }, [storedValue, storage, key]) | |
| return [storedValue, setStoredValue] | |
| } | |
| export const useLocalStorage = (key, initialValue) => { | |
| return useStorage(key, initialValue, window.localStorage) | |
| } | |
| export const useSessionStorage = (key, initialValue) => { | |
| return useStorage(key, initialValue, window.sessionStorage) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment