Last active
January 1, 2022 18:15
-
-
Save PaulieScanlon/433f3113e42da97339e6707278f9524c to your computer and use it in GitHub Desktop.
Sync state to local storage so that it persists through a page refresh. Usage is similar to useState except we pass in a local storage key so that we can default to that value on page load instead of the specified initial value.
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
import { useEffect, useState } from 'react' | |
const useLocalStorage = (key, initialValue) => { | |
const [storedValue, setStoredValue] = useState(initialValue) | |
const setValue = (value) => { | |
try { | |
const valueToStore = | |
value instanceof Function ? value(storedValue) : value | |
setStoredValue(valueToStore) | |
window.localStorage.setItem(key, JSON.stringify(valueToStore)) | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
useEffect(() => { | |
try { | |
const item = window.localStorage.getItem(key) | |
setStoredValue(item ? JSON.parse(item) : initialValue) | |
} catch (error) { | |
console.log(error) | |
return setStoredValue(initialValue) | |
} | |
}, []) | |
return [storedValue, setValue] | |
} | |
export default useLocalStorage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a modified version of useLocalStorage from https://usehooks.com/