Last active
February 23, 2021 03:01
-
-
Save diasjuniorr/ded10d1d957456a4400a2779b9fa10c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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