Skip to content

Instantly share code, notes, and snippets.

@brunobertolini
Created January 15, 2024 13:48
Show Gist options
  • Save brunobertolini/c0b46130f25d92df98ddc39b7d57c6c5 to your computer and use it in GitHub Desktop.
Save brunobertolini/c0b46130f25d92df98ddc39b7d57c6c5 to your computer and use it in GitHub Desktop.
A react useState with localStorage persistence
import { useEffect, useState } from 'react'
export const useStorage = (key, defaultValue) => {
const [value, setValue] = useState(() => {
const storedValue = typeof window !== 'undefined' && window?.localStorage.getItem(key)
return (storedValue && JSON.parse(storedValue)[key]) || defaultValue
})
useEffect(() => {
const valueToStore = { [key]: value }
console.log(valueToStore)
typeof window !== 'undefined' && window?.localStorage?.setItem(key, JSON.stringify(valueToStore))
}, [value, window])
return [value, setValue]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment