Skip to content

Instantly share code, notes, and snippets.

@httpJunkie
Last active May 14, 2020 11:00
Show Gist options
  • Save httpJunkie/a568e561b785a3ea1722467cd87af041 to your computer and use it in GitHub Desktop.
Save httpJunkie/a568e561b785a3ea1722467cd87af041 to your computer and use it in GitHub Desktop.
useLocalStorageState
/* https://stackblitz.com/edit/use-local-storage-state */
function useLocalStorageState(key, defaultValue) {
const [state, setState] = useState(() => {
let value
try {
value = JSON.parse(
window.localStorage.getItem('my-app-count') || JSON.stringify(defaultValue)
)
} catch (e) {
value = defaultValue;
}
return value;
})
useEffect(() => {
window.localStorage.setItem(key, state);
}, [state])
return [state, setState];
}
@azz0r
Copy link

azz0r commented May 14, 2020

For anyone who comes across this for usage, you need to adapt line 8

        window.localStorage.getItem(key) || JSON.stringify(defaultValue)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment