Skip to content

Instantly share code, notes, and snippets.

@marciobarrios
Last active July 16, 2019 11:44
Show Gist options
  • Save marciobarrios/07a13415f6c4bdb5576fd509547ee753 to your computer and use it in GitHub Desktop.
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)
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