Skip to content

Instantly share code, notes, and snippets.

@diasjuniorr
Last active February 23, 2021 03:01
Show Gist options
  • Save diasjuniorr/ded10d1d957456a4400a2779b9fa10c0 to your computer and use it in GitHub Desktop.
Save diasjuniorr/ded10d1d957456a4400a2779b9fa10c0 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react'
const UseLocalStorageState = (key: string, defaultValue: any) => {
const [state, setState] = useState(() => {
let val
try {
val = JSON.parse(window.localStorage.getItem(key) || String(defaultValue))
} catch (error) {
val = defaultValue
}
return val
})
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(state))
}, [state])
return [state, setState] as const
}
export default UseLocalStorageState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment