You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
750 B
JavaScript
34 lines
750 B
JavaScript
4 years ago
|
import {useState, useEffect} from 'react'
|
||
|
|
||
|
const init = {defined: false}
|
||
|
|
||
|
export default function useLocalStorage(key, defaultValue) {
|
||
|
const [state, setState] = useState(init)
|
||
|
|
||
|
// Load from localstorage on first render or if key changes
|
||
|
useEffect(() => {
|
||
|
const stored = window.localStorage.getItem(key)
|
||
|
|
||
|
try {
|
||
|
if(!stored) throw new Error('No stored value')
|
||
|
setState(JSON.parse(stored))
|
||
|
} catch {
|
||
|
setState(defaultValue)
|
||
|
}
|
||
|
}, [key])
|
||
|
|
||
|
// Persist to localstorage when state changes
|
||
|
useEffect(() => {
|
||
|
if(state === init) {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
window.localStorage.setItem(key, JSON.stringify(state))
|
||
|
}, [state])
|
||
|
|
||
|
if(state === init)
|
||
|
return [defaultValue, setState]
|
||
|
|
||
|
return [state, setState];
|
||
|
}
|