forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLocalStorage.ts
More file actions
36 lines (31 loc) · 912 Bytes
/
useLocalStorage.ts
File metadata and controls
36 lines (31 loc) · 912 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/hooks/useLocalStorage.ts
import { useCallback, useEffect, useRef, useState } from "react"
function useLocalStorage<T>(
key: string,
defaultValue: T
): [T, (value: T | ((prev: T) => T)) => void] {
const defaultValueRef = useRef(defaultValue)
const [state, setState] = useState<T>(defaultValue)
useEffect(() => {
try {
const stored = localStorage.getItem(key)
setState(stored !== null ? (JSON.parse(stored) as T) : defaultValueRef.current)
} catch {
setState(defaultValueRef.current)
}
}, [key])
const setValue = useCallback(
(value: T | ((prev: T) => T)) => {
setState((prev) => {
const next = value instanceof Function ? value(prev) : value
try {
localStorage.setItem(key, JSON.stringify(next))
} catch {}
return next
})
},
[key]
)
return [state, setValue]
}
export { useLocalStorage }