Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

PaulieScanlon commented Jan 1, 2022

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