Skip to content

Instantly share code, notes, and snippets.

@pauloremoli
Last active February 23, 2022 07:37
Show Gist options
  • Save pauloremoli/9a2751a65f7695db77465e91b5e042f0 to your computer and use it in GitHub Desktop.
Save pauloremoli/9a2751a65f7695db77465e91b5e042f0 to your computer and use it in GitHub Desktop.
Sticky react state - Persist state in local storage
// 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