Skip to content

Instantly share code, notes, and snippets.

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
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (error) {
useEffect(() => {
try {
const item = window.localStorage.getItem(key)
setStoredValue(item ? JSON.parse(item) : initialValue)
} catch (error) {
return setStoredValue(initialValue)
}, [])
return [storedValue, setValue]
export default useLocalStorage
Copy link

PaulieScanlon commented Jan 1, 2022

This is a modified version of useLocalStorage from

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