jarvis/dewey/hooks/useLocalStorage.ts

23 lines
579 B
TypeScript

import { useState, useEffect } from 'react'
export default function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
console.log(error)
return initialValue
}
})
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue))
} catch (error) {
console.log(error)
}
}, [key, storedValue])
return [storedValue, setStoredValue]
}