Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useLocalStorage.ts

47 lines950 Bytes

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 }
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]