Skip to content

Instantly share code, notes, and snippets.

@swyxio
Last active March 14, 2023 18:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swyxio/580495ee3e6f76602dad365fc203081b to your computer and use it in GitHub Desktop.
Save swyxio/580495ee3e6f76602dad365fc203081b to your computer and use it in GitHub Desktop.
SSR friendly version of useLocalStorage hook. you can also use this in a library https://github.com/astoilkov/use-local-storage-state
// usage
function Comp() {
const [language, setLanguage] = useLocalStorage('mykey', 'typescript')
}
// definition
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = React.useState(initialValue);
React.useEffect(() => {
// Get from local storage by key
const item = typeof window !== 'undefined' ? window.localStorage.getItem(key) : false
// Parse stored json or if none return initialValue
if (item) setStoredValue(JSON.parse(item))
}, [setStoredValue])
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = (value) => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment