Last active
May 14, 2020 11:00
-
-
Save httpJunkie/a568e561b785a3ea1722467cd87af041 to your computer and use it in GitHub Desktop.
useLocalStorageState
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
/* 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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For anyone who comes across this for usage, you need to adapt line 8