Open History to see the last commit
1import React from 'react'
2β
3const getItem = (key: string): unknown => {
4 try {
5 const itemValue = localStorage.getItem(key)
6 if (typeof itemValue === 'string') {
7 return JSON.parse(itemValue)
8 }
9 return undefined
10 } catch {
11 return undefined
12 }
13}
14β
15export default function useLocalStorage<T>(
16 key: string,
17 defaultValue: T | undefined
18): [T | undefined, (newVal: T | ((prevVal: T) => T)) => void] {
19 const [value, setValue] = React.useState<T>()
20β
21 React.useEffect(() => {
22 const initialValue = getItem(key) as T | undefined
23β
24 if (typeof initialValue === 'undefined' || initialValue === null) {
25 setValue(
26 typeof defaultValue === 'function' ? defaultValue() : defaultValue
27 )
28 } else {
29 setValue(initialValue)
30 }
31 }, [defaultValue, key])
32β
33 const setter = React.useCallback(
34 updater => {
35 setValue(old => {
36 let newVal = updater
37β
38 if (typeof updater == 'function') {
39 newVal = updater(old)
40 }
41 try {
42 localStorage.setItem(key, JSON.stringify(newVal))
43 } catch {}
44β
45 return newVal
46 })
47 },
48 [key]
49 )
50β
51 return [value, setter]
52}