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