Skip to content

Instantly share code, notes, and snippets.

@killa-kyle
Created June 28, 2021 03:33
Show Gist options
  • Save killa-kyle/e8c25c49cd3ba090f6f9125d550295fe to your computer and use it in GitHub Desktop.
Save killa-kyle/e8c25c49cd3ba090f6f9125d550295fe to your computer and use it in GitHub Desktop.
// https://www.joshwcomeau.com/react/persisting-react-state-in-localstorage/
function useStickyState(defaultValue, key) {
const [value, setValue] = React.useState(() => {
const stickyValue = window.localStorage.getItem(key);
return stickyValue !== null
? JSON.parse(stickyValue)
: defaultValue;
});
React.useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment