Last active
July 16, 2019 11:44
-
-
Save marciobarrios/07a13415f6c4bdb5576fd509547ee753 to your computer and use it in GitHub Desktop.
React Hook that uses localstorage to persist the state (https://dev.to/selbekk/persisting-your-react-state-in-9-lines-of-code-9go)
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
function usePersistedState(key, defaultValue) { | |
const [state, setState] = React.useState( | |
() => JSON.parse(localStorage.getItem(key)) || defaultValue | |
); | |
useEffect(() => { | |
localStorage.setItem(key, JSON.stringify(state)); | |
}, [key, state]); | |
return [state, setState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment