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