Skip to content

Instantly share code, notes, and snippets.

@PaulieScanlon
Last active January 1, 2022 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulieScanlon/433f3113e42da97339e6707278f9524c to your computer and use it in GitHub Desktop.
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.
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
@PaulieScanlon
Copy link
Author

This is a modified version of useLocalStorage from https://usehooks.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment