Created
June 28, 2021 03:33
-
-
Save killa-kyle/e8c25c49cd3ba090f6f9125d550295fe to your computer and use it in GitHub Desktop.
This file contains hidden or 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