Code by Robin Wieruch copied from his article
Last active
April 6, 2022 22:07
-
-
Save vogelino/856fc5d0832392c9bfdad84711732e4a to your computer and use it in GitHub Desktop.
React Hook: useLocalStorage
This file contains 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 useLocalStorage = (storageKey, fallbackState) => { | |
const [value, setValue] = React.useState( | |
JSON.parse(localStorage.getItem(storageKey)) || fallbackState | |
); | |
React.useEffect(() => { | |
localStorage.setItem(storageKey, JSON.stringify(value)); | |
}, [value, storageKey]); | |
return [value, setValue]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment